2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP+MySQLをCloud Foundryで動かす

Last updated at Posted at 2012-04-18

環境変数$_SERVER["VCAP_SERVICES"]に入ってるjsonからmysqlへの接続情報(ホスト、ポート、ユーザー名、パスワード、データベース名)が取得できます。

ということで最もシンプルな例を:

index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>simplest php + mysql </title>
</head>
<body>
<h1>we love php! </h1>
<?php
$dbinfo = json_decode($_SERVER["VCAP_SERVICES"],TRUE);
$key = $dbinfo["mysql-5.1"][0]["credentials"];

$con = mysql_connect($key["host"].":".$key["port"], $key["username"], $key["password"]);
$res = mysql_select_db($key["name"],$con);

$result = mysql_query('select * from posts');
if(!$result) {
  die(mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
    print('<h2>');
    print($row['title']);
    print('</h2>');
    print('<p>');
    print($row['description']);
    print('</p>');
}
?>

</body>
</html>

クラウド上にアップする

前準備:Ruby1.9(またはRuby1.8とrubygems)がインストール済みとして下記にてvmcコマンドをインストール

$ gem install vmc

準備ができたら、上で作ったphpファイルのあるディレクトリにて下記のコマンドを実行

$ vmc target xxx.yyyyyy.com  #<- おつかいのクラウドのapiホスト名
$ vmc login 
  # ユーザー名とパスワードを入力
$ vmc push your_app_name

とすると対話型が立ち上がるので下記のように進むとOK。(対話型なので入力してるのは'y'とか'3'くらいです)

$ vmc push  simple-php
Would you like to deploy from the current directory? [Yn]: y
Application Deployed URL [simple-php.foobar.com]: 
# デフォルトではアプリ名をサブドメインとしてはホスト名が発行される
Detected a PHP Application, is this correct? [Yn]: y
# 自動で何で書かれたアプリか判別される
Memory Reservation (64M, 128M, 256M, 512M, 1G, 2G) [128M]: 
Creating Application: OK
Would you like to bind any services to 'simple-php'? [yN]: y
# サービスとはRDBやmemcacheなどアプリにひもづける外部DB的なものの総称です
# MySQLをバインドするのでこの質問は"y"
Would you like to use an existing provisioned service? [yN]: n
# 他のアプリにひもづけられたサービス(DB等)をひもづけますか?
# 今回は新規に作成するので"n"
The following system services are available
1: memcached
2: mongodb
3: mysql
4: postgresql
5: redis
Please select one you wish to provision: 3
# 3のmysqlを選択する
Specify the name of the service [mysql-7f019]: mysql-test
# 適当に名前をつける
# ここまでで設定は終了。あとはズラズラっとアップロードしてDBが準備されてアプリが起動する
Creating Service: OK
Binding Service [mysql-test]: OK
Uploading Application:
  Checking for available resources: OK
  Packing application: OK
  Uploading (1K): OK   
Push Status: OK
Staging Application: OK                                                         
Starting Application: OK                                                        

これで完了。
ブラウザで払い出されたURLにアクセスすると動いていることがすぐ確認できます

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?