Connecting PHP to Compose for MySQL on Bluemix


When we noticed an article about how to connect Compose for MySQL on Bluemix with PHP, we just had to make sure more people saw how simple it was. So over to Lorna Jane, who's allowed us to cross post her blog post.

Most of the PHP I write runs on Bluemix - it's IBM self-service cloud, and since I work there, they pay for my accounts :) There are a bunch of databases you can use there, mostly open source offerings, and of course, with PHP I like to use MySQL. Someone asked me for my connection code since it's a bit tricky to grab the credentials that you need, so here it is.

Bluemix Environment Variables

In Bluemix, you can simply create a MySQL database (look for "compose-for-mysql" in the catalog), create a set of credentials, and then bind it to your app. I should blog a few more of my PHP-on-Bluemix tricks but you can run a selection of PHP versions and it's also possible to add extensions that you need, I have found it does have what I need once I figure out how to configure it!

Once the database is bound to the application, then your PHP code running on Bluemix will have an environment variable called VCAP_SERVICES. The variable contains a JSON string, with top-level elements for each of the services that are bound to your application. Services will usually be the databases you are using but could also be some of the APIs for example.

I like to decode VCAP_SERVICES to an array so I can work with it, like this:

$vcap_services = json_decode($_ENV['VCAP_SERVICES'], true);

Get PDO Connected

To connect to PDO with MySQL, we need to supply a few different values:

The VCAP_SERVICES supplies a URL containing all those elements, but not splitting them out. The PHP function parse_url() can help us with this. Here's the full code block that I use to connect in my applications:

$vcap_services = json_decode($_ENV['VCAP_SERVICES'], true);
$uri = $vcap_services['compose-for-mysql'][0]['credentials']['uri'];
$db_creds = parse_url($uri);
$dbname = "your_database_name";

$dsn = "mysql:host=" . $db_creds['host'] . ";port=" . $db_creds['port'] . ";dbname=" . $dbname;
$db = new PDO($dsn, $db_creds['user'], $db_creds['pass']);

Hopefully, you can just borrow the code above and quickly get started with your own PHP/MySQL applications.

Lorna is based in Yorkshire, UK; she is a Developer Advocate with IBM Watson Data Platform, a published author and experienced conference speaker. She brings her technical expertise on a range of topics to audiences all over the world with her writing and speaking engagements, always delivered with a very practical slant. In her spare time, Lorna blogs at

attribution Émile Perron

Conquer the Data Layer

Spend your time developing apps, not managing databases.