PHP (PDO) Connection to Cloud SQL on Google App Engine Not Working

折月煮酒 提交于 2019-12-11 08:35:48

问题


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);


来源:https://stackoverflow.com/questions/50541460/php-pdo-connection-to-cloud-sql-on-google-app-engine-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!