Connect to Cloud SQL via PHP hosted on Compute Engine

-1

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

• I have a MySQL instance in Cloud SQL called bd-vendas , and I created a database named vendas in it.

• I have a Linux Debian VM built on Compute Engine.

Note: I would like to make the connection using PDO

I tried this but it did not work:

<?php
    function getConnection(){
        try {
          $connection = new PDO('mysql:host=999.999.999.99;dbname=vendas', 'usuario', 'senha');
          $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');
?>
    
asked by anonymous 08.08.2018 / 19:56

1 answer

0

I resolved by changing the connection string as follows:

<?php
    function getConnection(){
        try {                                {GCSQL IPv4}                {Nome da conexao da instância}            {Nome banco}
          $connection = new PDO('mysql:host=999.999.999.99;unix_socket=/cloudsql/instance:bd-instance;charset=utf8;dbname=vendas', 'usuario', 'senha');
          $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');
?>    
    
09.08.2018 / 18:34