Connect to Cloud SQL via PHP hosted on Compute Engine

Asked

Viewed 177 times

-1

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

• I have a Mysql instance in Cloud SQL called bd-vendas and in it I created a bank called vendas.

• I own a Debian Linux VM created on the Compute Engine.

Note: I would like to make the connection using PDO

I tried that, but it didn’t 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');
?>

1 answer

0


I decided to change 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');
?>    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.