How do I connect and retrieve data from Google Cloud SQL using PHP?

给你一囗甜甜゛ 提交于 2021-02-10 09:37:08

问题


The only tutorials I could find used unfamiliar alternative resources, like app engine, composer, github, proxies, other plugins.

Isn't it possible to simply connect to it using pure PHP?

For example, in the following code would I need to modify to get data from Google Cloud SQL?

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

回答1:


Google App Engine connects from inside of Google servers to the Cloud SQL instance via proxy, but the Cloud SQL instance is just a managed MySQL instance. So, if you want just to connect from the outside with PHP code and without a proxy, then you just need to authorize your IP (here: https://cloud.google.com/sql/docs/mysql/connect-external-app#appaccessIP) in the Cloud SQL instance.

And then, you should modify the code to change “localhost” to your Google Cloud SQL instance public IP (with its proper username, password and dbname). You can find the public IP here: http://console.cloud.google.com/sql/instances/

But, if you still want to have a look around PHP on Google App Engine, check that link https://cloud.google.com/appengine/docs/standard/php/cloud-sql/using-cloud-sql-mysql



来源:https://stackoverflow.com/questions/50340559/how-do-i-connect-and-retrieve-data-from-google-cloud-sql-using-php

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