Search code examples
phpmysqlgoogle-app-enginemysqligoogle-cloud-sql

Connecting to Google Cloud SQL in Google App Engine


Basically I am deploying an simple website that has register and login. I have deployed into AppEngine and my Cloud SQL is in the same AppEngine Project. Project: http://cc-lab4.appspot.com/register.php

I created database and table in Cloud SQL, I want my register.php to connect to the cloud sql database and perform insert query.

I really want to use mysqli_connect() since I am familiar with this, PDO connection is new to me.

I don't know the exact way of connecting yet, havent been successfull at all. Anyone have idea how to use mysqli_connect() to Cloud SQL would be great.

After Editing by using one of the answers, still didn't work: Cloud SQL Database Instance

 //Variables for Database connection
 $user = "root";
 $pw = "root";
 $socket = '/cloudsql/'. $ENV{"cc-lab4:australia-southeast1:my-sql-artworks"};
 $dbname = "artworks";

 //Registration values from <Form>
 $username = $_POST['username'];
 $password = $_POST['password'];

 //Database connection
 $db = mysqli_connect(NULL, $user, $pw, $dbname, NULL, $socket);

 if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
 }

 //Table Member (id, username,password,reg_date)
 $q = "insert into member values(null, '$username', SHA('$password'), now())";
 mysqli_query($db, $q); 

Solution

  • In the end, I managed to connect to my Cloud SQL with PDO method.

    $dsn = getenv('MYSQL_DSN');
    $user = getenv('MYSQL_USER');
    $pw = getenv('MYSQL_PASSWORD');
    
    //Database connection
    $db = new PDO($dsn, $user, $pw);
    
    //register value from <form> inputs
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    //insertion success
    $statement = $db->prepare("insert into member values(null, '$username', SHA('$password'), now())");
    $statement->execute();
    

    My .yaml file configuration enter image description here