Search code examples
phpgoogle-app-enginegoogle-cloud-platformgoogle-cloud-sql

Unable to Connect Google App Engine and Google Cloud SQL


I have been trying to connect to the sample PHP hello world app running in Google App Engine to Google Cloud SQL.

Im trying to test a sample database connection. Using an external client like Navicat I can get access, however, connecting the app directly to cloud sql is not working.

I have reviewed numerous stackoverflow similar problems and thoroughly worked through the examples provided by google, with no luck.

Here you can see the hello world file with the output of three different attempts to connect to the sql db, I am echoing the json of each object as well.... which is coming back empty or null.

https://beaming-glyph-107521.appspot.com/ enter image description here

Im not sure what else to do here

My Google App has access to the Cloud SQL instance: enter image description here

I right now my user sql user is root and the password blank, but Ive also tried a user with a defined password - still with no luck.

     <?php

     ini_set('display_errors',1);
     ini_set('display_startup_errors',1);
     error_reporting(-1);

       echo 'Hello, world!';

     //Copied and Pasted straight from the provided connection strings in Cloud SQL
     // Using PDO_MySQL (connecting from App Engine)
     $db = new pdo('mysql:unix_socket=/cloudsql/beaming-glyph-107521:testdb',
         'root',  // username
         ''       // password
     );

     // Using mysqli (connecting from App Engine)
     $sql = new mysqli(
         null, // host
         'root', // username
         '',     // password
         '', // database name
         null,
         '/cloudsql/beaming-glyph-107521:testdb'
     );

     // Using MySQL API (connecting from App Engine)
     $conn = mysql_connect(':/cloudsql/beaming-glyph-107521:testdb',
         'root', // username
         ''      // password
     );

     echo "<br><br/>pdo connection: ".json_encode($db);
     echo'<br><br/> msqli connection: '.json_encode($sql);
     echo '<br><br/> mysql conn: '.json_encode($conn);

Solution

  • The problem is in using jsonencode() to display the db object. For whatever reason it was showing it as blank, when in fact it actually existed. After several more hours of investigation I was able to run a query and display the results immediately after the db object was created.

    So in conclusion, looks like I've been connecting all along. If you are trying to debug a db connection try running a test query and displaying the results immediately after creating the db object to test the connection.

        $db = new pdo('mysql:unix_socket=/cloudsql/table-1075:testdb;dbname=sampledb',
    'root',  // username
    ''       // password
      );
    
     var_dump($db);
     $sql='SELECT * FROM table';
     foreach ($db->query($sql) as $row) {
     print $row['Index'] . "\t";
    
     }