Connecting PHP to MySQL on Bluemix

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:

  • host
  • port
  • username
  • password
  • database name

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.

Before you go: was this helpful? confusing? annoying and you’d rather have it as a library you can just pull in with Composer (I can do that if I know you’d find it useful)? Please leave me a comment so I know!

3 thoughts on “Connecting PHP to MySQL on Bluemix

  1. Pingback: Using PostgreSQL with PHP in Cloud Foundry – Rob Allen's DevNotes

  2. Hi, Can we do it non pdo way(the traditional way ;-)) .I have been using cleardb mysql from few years,now came to know its being deprecated by IBM.So planning to go for compose mysql.Also can you provide examples on CRUD and Registration/Login.
    Thanks Lorna.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.