rish626509
rish626509

Reputation: 25

Unable to connect PHP to db2 in bluemix

I am very much new to PHP programming and bluemix as well. I was looking for connecting to PHP to bluemix. For that I created SQL DB (DB2 database) in Bluemix and bind it to my app also. Then got the credentials and used it in php using db2_connect(). It didnt work and returned connection failed.

After that I got this:

$vcap_services = json_decode($_ENV["VCAP_SERVICES" ]); $db = $vcap_services->{'mysql-5.5'}[0]->credentials; $mysql_database = $db->name; $mysql_port=$db->port; //$mysql_server_name ='${db->host}:${db->port}'; $mysql_server_name =$db->host . ':' . $db->port; $mysql_username = $db->username; $mysql_password = $db->password;

$con = mysql_connect($mysql_server_name, $mysql_username, $mysql_password);

My question is, should I replace mysql with db2? Or it'll run like this just changing mysql-5.5 to sqldb?

I used db2_connect also and it is not working.

Upvotes: 2

Views: 364

Answers (2)

whitfiea
whitfiea

Reputation: 1943

For connecting to the SQLDB service in Bluemix you must use db2_connect rather than mysql_connect, the docs are here. As this is a remote database then you must use a connection string rather than separate databaseName, userName parameters.

Here is an example of how to parse the VCAP_SERVICES and connect to the SQLDB service in PHP:

# Decode JSON and gather DB Info
$services_json = json_decode($json,true);
$sqldb = $services_json["sqldb"];
if (empty($sqldb)) {
    echo "No sqldb service instance is bound. Please bind a sqldb service instance";
    return;
}

$sqldb_config = $services_json["sqldb"][0]["credentials"];

// create DB connect string
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=".
   $sqldb_config["db"].
   ";HOSTNAME=".
   $sqldb_config["host"].
   ";PORT=".
   $sqldb_config["port"].
   ";PROTOCOL=TCPIP;UID=".
   $sqldb_config["username"].
   ";PWD=".
   $sqldb_config["password"].
   ";";


// connect to database
$conn = db2_connect($conn_string, '', '');

Upvotes: 3

herchu
herchu

Reputation: 946

You should not use $mysql_connect, this is MySQL-specific. Use $db2_connect, see the docs for references.

In addition, you are most likely using the wrong credentials (or: an empty object instead). Check the service name from your Bluemix console (expand the service credentials under the service instance in your app screen): most likely they are not "mysql-5.5". I recommend you just print $vcap_services to a console or as debug output in your HTML, and see how it looks like to get the right server/port/user/password.

Upvotes: 0

Related Questions