1
votes

How do I connect to an instance of Cloud SQL through a php file hosted on a Compute Engine VM?

• I have a MySQL (1º generation) instance in the Cloud SQL called bd-sales and a database called sales

• I have a Linux(Debian) VM built in Compute Engine

Obs.: I would like to make the connection using PDO

I tried this, but it didn't works:

<?php
    function getConnection(){
        try {
          $connection = new PDO('mysql:host=999.999.999.99;dbname=sales', 'user', 'pass');
          $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          return $connection;
          } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
            return;
        }
    }

    header("Access-Control-Allow-Origin: *");
    header('Content-Type: application/json');
?>
1

1 Answers

1
votes

I solved the problem, changing the connection string:

<?php
    function getConnection(){
        try {                                {GCSQL IPv4}                         {instance name}                 {Database name}
          $connection = new PDO('mysql:host=999.999.999.99;unix_socket=/cloudsql/instance:bd-instance;charset=utf8;dbname=vendas', 'user', 'pass');
          $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          return $connection;
          } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
            return;
        }
    }

header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

?>