Connecting PHP to MySQL on Bluemix

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:

1
$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:

READ  Autocomplete textbox using jQuery, PHP and MySQL
1
2
3
4
5
6
7
$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!