PHP (PDO) Connection to Cloud SQL on Google App En

2019-08-04 18:39发布

问题:

I am experiencing issues connecting to a Cloud SQL instance hosted in an App engine flexible environment which shares same project. I am using PHP Data Object (PDO) to create the connection. I Kept getting this error:

SQLSTATE[HY000] [2002] No such file or directory

Even when I had done all the settings as to authorizing the app, etc.

Here is my sample code:

public function __construct() {
    try {

        $this->datab = new PDO('mysql:unix_socket=/cloudsql/<MY INSTANCE CONNECTION NAME>;dbname=MY_DATABASE', 'USERNAME', 'PASSWORD');

        $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        $this->isConnected = false;
        throw new Exception($e->getMessage());
    }
}

Please, is there anything I need do for it to work? I'm really stock now and I do need help.

Thank you in advance.

回答1:

Try this one

  in app.yaml
  env_variables:
  MYSQL_USER: username
  MYSQL_PASSWORD: password
  MYSQL_DSN: mysql:unix_socket=/cloudsql/instancename;dbname=yourdbname

  in your script:
  $dsn=getenv('MYSQL_DSN');
  $user=getenv('MYSQL_USER');
  $pass=getenv('MYSQL_PASSWORD');
  $dbh = new PDO($dsn, $user, $pass);