Search code examples
phpdb2ibm-cloud

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.


Solution

  • 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, '', '');