Connecting to MySQL database on Google Cloud from localhost application

  google-cloud-sql, localhost, mysql, php

I have recently set up a MySQL database on Google Cloud. I have whitelisted my IP address and can connect to it using MySQL workbench without any problems.

I am developing a PHP application, which I run on localhost:8000. Things worked fine when I was connecting to a local MySQL instance, however I run into problems when trying to connect to the Google Cloud instance.

It seems that a connection is being made (I tried deliberately connecting with the wrong hostname and get a ‘No such host is known’ error). Using the IP address : port number of the Google Cloud instance, I get problems with the tables not being recognised, which I assume means that I have connected to the host but it is failing to pick up on the schema properly.

I was wondering if this problem is due to the fact that the connection is being called from the localhost and I need to set something up on Google Cloud to allow this.

Could anybody tell me

(1) If this is likely to be the problem and, if so,

(2) How do I allow access from localhost on Google?

For further information, I connect using

pdo = new PDO($dsn, "root", <password>, $options);

where

$dsn = "mysql:host=<ip-address>:<port>;dbname=<schema-name>;"

and

$options = [
   PDO::ATTR_PERSISTENT => false,
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
   PDO::ATTR_STRINGIFY_FETCHES => false
];

The following worked fine on the local instance:

$dsn = "mysql:host=localhost:3306;dbname=<schema-name>;"

Thanks in advance!

Source: Ask PHP

LEAVE A COMMENT