Skip to content

Instantly share code, notes, and snippets.

@mayankchourasia
Created September 13, 2020 15:05
Show Gist options
  • Save mayankchourasia/3f638873dece8626f2db1a7b359eb906 to your computer and use it in GitHub Desktop.
Save mayankchourasia/3f638873dece8626f2db1a7b359eb906 to your computer and use it in GitHub Desktop.
runtime: php72
env_variables:
# Replace USER, PASSWORD, DATABASE, and CONNECTION_NAME with the
# values obtained when configuring your Cloud SQL instance.
CLOUDSQL_USER: Unique Name
CLOUDSQL_PASSWORD: Unique Password
CLOUDSQL_DSN: "mysql:dbname=<strong>Unique Name</strong>;unix_socket=/cloudsql/<strong>Unique Name:Location you Selected :my-demo-database-instance</strong>"
# [END gae_cloudsql_mysql_env]
<?php
// Ensure the required environment variables are set to run the application
if (!getenv('CLOUDSQL_DSN') || !getenv('CLOUDSQL_USER') || false === getenv('CLOUDSQL_PASSWORD')) {
die('Set CLOUDSQL_DSN, CLOUDSQL_USER, and CLOUDSQL_PASSWORD environment variables');
}
# [START gae_cloudsql_example]
// If the unix socket is unavailable, try to connect using TCP. This will work
// if you're running a local MySQL server or using the Cloud SQL proxy, for example:
// $ cloud_sql_proxy -instances=your-connection-name=tcp:3306
// This will mean your DSN for connecting locally to Cloud SQL would look like this:
// for MySQL
// $dsn = "mysql:dbname=DATABASE;host=126.0.0.1";
// // for PostgreSQL
// $dsn = "pgsql:dbname=DATABASE;host=126.0.0.1";
$dsn = getenv('CLOUDSQL_DSN');
$user = getenv('CLOUDSQL_USER');
$password = getenv('CLOUDSQL_PASSWORD');
// create the PDO client
$db = new PDO($dsn, $user, $password);
// create the tables if they don't exist
$sql = 'CREATE TABLE IF NOT EXISTS contacts (name VARCHAR(255), phone VARCHAR(255), email VARCHAR(255))';
$stmt = $db->prepare($sql);
$stmt->execute();
# [END gae_cloudsql_example]
?>
<?php
require_once 'config.php';
# [START gae_simple_front_controller]
switch (@parse_url($_SERVER['REQUEST_URI'])['path']) {
case '/':
case '/contacts.php':
require 'contacts.php';
break;
case '/contact-add.php':
require 'contact-add.php';
break;
default:
http_response_code(404);
exit('Not Found');
}
# [END gae_simple_front_controller]
contacts.php
<?php
// Query existing entries.
$results = $db->query('SELECT * FROM contacts');
?>
<html>
<body>
<h2>Contacts</h2>
<a href="/contact-add.php">Add New</a>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php if ($results->rowCount() > 0) { ?>
<?php foreach ($results as $row) { ?>
<tr>
<td><?= $row['name'] ?></td>
<td><?= $row['phone'] ?></td>
<td><?= $row['email'] ?></td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</body>
</html>
@mayankchourasia
Copy link
Author

Connect Google App Engine With Google Cloud SQL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment