LoginSignup
64
57

More than 5 years have passed since last update.

HerokuでPHP+MySQL

Last updated at Posted at 2014-05-18

同内容の記事をTumblrで、コードはgithubで公開しています。

HerokuでMySQLを使用するためにはClearDBアドオンを導入する必要があります。
ClearDBは、MySQLで動くアプリケーションのためのサービスで、Herokuではアドオンから簡単に利用できます。

手順

composer.jsonを作成

Herokuのアプリを作成するために、作業ディレクトリでcomposer.jsonを作成します。

composer.json
{
    "require": {
        "php": "~5.5.0"
    }
}

gitを初期化して、composer.jsonをコミットします。

$ git init
$ git add composer.json
$ git commit -m 'initial commit'

ClearDBアドオンを導入

Herokuのアプリを作成して、composer.jsonをデプロイします。

$ heroku create
$ git push heroku master

ClaerDBのアドオンをインストールします。

$ heroku addons:add cleardb:ignite

これで作成したアプリ用のClearDBデータベースの作成と、その情報がHerokuに設定されています。

ClearDBの設定

設定されたClearDBのURLをHerokuから取得します。

$ heroku config | grep CLEARDB_DATABASE_URL

実行結果は以下のようになります。

2:CLEARDB_DATABASE_URL: mysql://(--username--):(--password--)@(--hostname--)/(--dbname--)?reconnect=true

取得したusername, password, hostname, dbnameを使用して、ClearDBに接続します。

$ mysql --host=(--hostname--) --user=(--username--) --password=(--password--) (--dbname--)

例としてuserテーブルを作成し、レコードを3つ登録します。

mysql> create table user (
    id int primary key auto_increment,
    name varchar(64),
    data_created DATETIME
);
mysql> insert into user values (1, 'user1', now());
mysql> insert into user values (2, 'user2', now());
mysql> insert into user values (3, 'user3', now());
mysql> select * from user;
+----+-------+---------------------+
| id | name  | data_created        |
+----+-------+---------------------+
|  1 | user1 | 2014-01-01 00:00:00 |
|  2 | user2 | 2014-01-01 00:00:00 |
|  3 | user3 | 2014-01-01 00:00:00 |
+----+-------+---------------------+

index.phpを作成

作成したClearDBに接続するためのindex.phpを以下のように作成します。

index.php
<?php
    $url = parse_url(getenv("CLEARDB_DATABASE_URL"));

    $server = $url["host"];
    $username = $url["user"];
    $password = $url["pass"];
    $db = substr($url["path"], 1);

    $link = mysqli_connect($server, $username, $password, $db);
    $result = mysqli_query($link, "select * from user");

    while($user = mysqli_fetch_array($result)) {
      echo $user['id'], " : ", $user['name'], "<br>";
    }
?>

index.phpをHerokuにデプロイします。

$ git add index.php
$ git commit -m 'add index.php'
$ git push heroku master

ブラウザでデプロイ先にアクセスし、以下のように表示されていれば成功です。

1 : user1
2 : user2
3 : user3

関連リンク

64
57
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
64
57