我正在尝试用PHP连接到我的Google Cloud SQL实例(我使用的是PDO(。当运行我的PHP文件(来自谷歌云终端(时,我收到以下错误:
Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in /home/bob_brown_the_dev/index.php:17
Stack trace:
#0 /home/bob_brown_the_dev/index.php(17): PDO->__construct('mysql:dbname=ma...', 'root', '', NULL)
#1 {main}
thrown in /home/bob_brown_the_dev/index.php on line 17
这就是我的PHP文件的样子:
<?php
$username = 'root';
$password = getenv("MYSQL_PASS");
$dbName = 'main';
$connectionName = getenv("INSTANCE_CONNECTION_NAME");
$socketDir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';
$dsn = sprintf(
'mysql:dbname=%s;unix_socket=%s/%s',
$dbName,
$socketDir,
$connectionName
);
// Connect to the database.
$conn = new PDO($dsn, $username, $password, $conn_config);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
这就是我的app.yaml文件的样子:
runtime: php73
entrypoint:
serve index.php
env_variables:
APP_DEBUG: true
LOG_CHANNEL: stderr
APP_STORAGE: /tmp
INSTANCE_CONNECTION_NAME: "<instance-id>:us-west2:<name>"
DB_SOCKET_DIR: "/cloudsql/<instance-id>:us-west2:<name>"
MYSQL_PASS: <password>
DB_CONNECTION: mysql
beta_settings:
cloud_sql_instances: "<instance-id>:us-west2:<name>"
提前感谢您的帮助!
编辑:
当我提取环境变量时,似乎出现了问题。一旦我解决了这个问题,错误就变成了:
Uncaught PDOException: SQLSTATE[HY000] [2002] Not a directory in /home/bob_brown_the_dev/index.php:17
Stack trace:
#0 /home/bob_brown_the_dev/index.php(17): PDO->__construct('mysql:host=loca...', '...', '...')
#1 {main}
thrown in /home/bob_brown_the_dev/index.php on line 17
当我返回DSN时,它是这样的:
mysql:dbname=main;unix_socket=/cloudsql/<name>:us-west2:<other name>/<name>:us-west2:<other name>
如果您在Cloud Shell中运行应用程序,则需要启动Cloud SQL Auth Proxy来模拟应用程序引擎为您所做的工作。
像这样启动代理:
$ cloud_sql_proxy -instances=<project-id>:us-west2:<instance-name> -dir /cloudsql
注意,如果/cloudsql
不存在,您将不得不手动创建它。