Help us understand the problem. What is going on with this article?

OpenShift で PHP から MySQL 5.5 を使う

More than 5 years have passed since last update.

PHP 5.4 の Web アプリを OpenShift で動かす - Qiita の続き。

Composerを使うには PHP - OpenShift で Composer を使う - Qiita を参照のこと。

MySQL のカートリッジを追加する

rhc を使う。-a でアプリケーション名を指定する。ここではアプリケーション名は hello だとして説明する。

$ rhc cartridge add mysql-5.5 -a hello

Adding mysql-5.5 to application 'hello' ... done

mysql-5.5 (MySQL 5.5)
---------------------
  Gears:          Located with php-5.4
  Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
  Database Name:  hello
  Password:       xxxxxxxxxxxx
  Username:       xxxxxxxxxxxx

MySQL 5.5 database added.  Please make note of these credentials:

       Root User: xxxxxxxxxxxx
   Root Password: xxxxxxxxxxxx
   Database Name: hello

Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/

You can manage your new MySQL database by also embedding phpmyadmin.
The phpmyadmin username and password will be the same as the MySQL credentials
above.

環境変数を使って PHP から MySQL にアクセスする

MySQL Overview | OpenShift Developers にあるように、PHP からデータベースにアクセスするために必要な情報は環境変数に設定されている。

Reading Environment Variables: Examples にあるように、getenv() 関数を使って参照する。

example.php
$env_var = getenv('OPENSHIFT_ENV_VAR');

具体的なコードは次の通り。

db.php
<?php
$host = getenv('OPENSHIFT_MYSQL_DB_HOST');
$port = getenv('OPENSHIFT_MYSQL_DB_PORT');
$user = getenv('OPENSHIFT_MYSQL_DB_USERNAME');
$password = getenv('OPENSHIFT_MYSQL_DB_PASSWORD');
$dbname = 'ranking';

$pdo = new \PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8", $user, $password, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$stmt = $pdo->query("select 1 + 1");
var_dump($stmt->fetchAll());

git add/commit/push でソースコードを登録する。

(Composerを有効にしているので、ログが出力されている)

$ git add db.php
$ git commit -m 'setup mysql'
$ git push
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 341 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Stopping MySQL 5.5 cartridge
remote: Stopping PHP 5.4 cartridge (Apache+mod_php)
remote: Waiting for stop to finish
remote: Waiting for stop to finish
remote: Building git ref 'master', commit a10e970
remote: Checking .openshift/pear.txt for PEAR dependency...
remote: Checking composer.json for Composer dependency... 
remote: Loading composer repositories with package information
remote: Installing dependencies (including require-dev) from lock file
remote:   - Installing react/promise (v2.2.0)
remote:     Loading from cache
remote: 
remote:   - Installing guzzlehttp/streams (3.0.0)
remote:     Loading from cache
remote: 
remote:   - Installing guzzlehttp/ringphp (1.0.5)
remote:     Loading from cache
remote: 
remote:   - Installing guzzlehttp/guzzle (5.2.0)
remote:     Loading from cache
remote: 
remote: Generating autoload files
remote: Preparing build for deployment
remote: Deployment id is 25533d8a
remote: Activating deployment
remote: Starting MySQL 5.5 cartridge
remote: Starting PHP 5.4 cartridge (Apache+mod_php)
remote: Application directory "/" selected as DocumentRoot
remote: -------------------------
remote: Git Post-Receive Result: success
remote: Activation status: success
remote: Deployment completed with status: success
To ssh://54e95c645973ca95f10000b9@ranking-takatama.rhcloud.com/~/git/ranking.git/
   3fb69d6..a10e970  master -> master

http://hello-<ネームスペース名>.rdcloud.com/db.php にアクセスした結果は次の通り。

array(1) { [0]=> array(1) { ["1 + 1"]=> string(1) "2" } }

もしも上手く動かない時は

rhc tail コマンド、もしくは rhc ssh コマンドで apache や mysql のログを確認できる。

参考: How do I troubleshoot application issues using the logs? – Help Center

$ rhc tail -a hello
==> app-root/logs/php.log <==
[Sun Feb 22 04:32:38 2015] [notice] Digest: generating secret for digest authentication ...
...

==> app-root/logs/mysql.log <==
150222  4:32:19 InnoDB: highest supported file format is Barracuda.
...
$ rhc ssh -a hello
Connecting to ...
    ******************************************************************

    You are accessing a service that is for use only by authorized users.
...

> cd $OPENSHIFT_LOG_DIR 
> ls
mysql.log  php.log
> less mysql.log 
> exit

ローカル開発環境にもMySQLと環境変数を準備すれば動作させられるとは思うんだけれど、試していません。

takatama
東京で働くソフトウェアエンジニアです。
https://twitter.com/takatama_jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away