Skip to content

Commit ac7e74a

Browse files
committed
feat: add mysql sample
1 parent 8e3b542 commit ac7e74a

File tree

6 files changed

+372
-0
lines changed

6 files changed

+372
-0
lines changed

cloud_sql/mysql/pdo/README.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Connection to Cloud SQL - MySQL
2+
3+
## Before you begin
4+
5+
1. Before you use this code sample, you need to have [Composer](https://getcomposer.org/) installed or downloaded into this folder. Download instructions can be found [here](https://getcomposer.org/download/).
6+
2. Create a MySQL Cloud SQL Instance by following these [instructions](https://cloud.google.com/sql/docs/mysql/create-instance). Note the connection string, database user, and database password that you create.
7+
3. Create a database for your application by following these [instructions](https://cloud.google.com/sql/docs/mysql/create-manage-databases). Note the database name.
8+
4. Create a service account with the 'Cloud SQL Client' permissions by following these [instructions](https://cloud.google.com/sql/docs/mysql/connect-external-app#4_if_required_by_your_authentication_method_create_a_service_account). Download a JSON key to use to authenticate your connection.
9+
5. Use the information noted in the previous steps:
10+
11+
```bash
12+
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
13+
export CLOUD_SQL_CONNECTION_NAME='::'
14+
export DB_USER='my-db-user'
15+
export DB_PASS='my-db-pass'
16+
export DB_NAME='my-db-name'
17+
export DB_HOSTNAME='localhost'
18+
```
19+
20+
Note: Saving credentials in environment variables is convenient, but not secure - consider a more secure solution such as [Cloud KMS](https://cloud.google.com/kms/) to help keep secrets safe.
21+
22+
## Running Locally
23+
24+
To run this application locally, download and install the `cloud_sql_proxy` by following the instructions [here](https://cloud.google.com/sql/docs/mysql/sql-proxy#install).
25+
26+
Once the proxy is ready, use one of the following commands to start the proxy in the background.
27+
28+
You may connect to your instance via either unix sockets or TCP. To connect using a socket, you must provide the `-dir` option when starting the proxy. To connect via TCP, you must provide a port as part of the instance name. Both are demonstrated below.
29+
30+
#### Unix Socket mode
31+
32+
```bash
33+
$ ./cloud_sql_proxy -dir=/cloudsql \
34+
--instances=$CLOUD_SQL_CONNECTION_NAME \
35+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
36+
```
37+
38+
Note: Make sure to run the command under a user with write access in the `/cloudsql` directory. This proxy will use this folder to create a unix socket the application will use to connect to Cloud SQL.
39+
40+
#### TCP mode
41+
42+
```bash
43+
$ ./cloud_sql_proxy \
44+
--instances=$CLOUD_SQL_CONNECTION_NAME=tcp:3306 \
45+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
46+
```
47+
48+
Execute the following:
49+
50+
```bash
51+
$ php -S localhost:8080
52+
```
53+
54+
Navigate towards http://localhost:8080 to verify your application is running correctly.
55+
56+
## Google App Engine Standard
57+
58+
To run on GAE-Standard, create an App Engine project by following the setup for these [instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
59+
60+
First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
61+
62+
Next, the following command will deploy the application to your Google Cloud project:
63+
64+
```bash
65+
$ gcloud app deploy
66+
```

cloud_sql/mysql/pdo/app.yaml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
runtime: php72
16+
17+
# Remember - storing secrets in plaintext is potentially unsafe. Consider using
18+
# something like https://cloud.google.com/kms/ to help keep secrets secret.
19+
env_variables:
20+
CLOUD_SQL_CONNECTION_NAME: ::
21+
DB_USER: my-db-user
22+
DB_PASS: my-db-pass
23+
DB_NAME: my_db
24+
25+
# Defaults to "serve index.php" and "serve public/index.php". Can be used to
26+
# serve a custom PHP front controller (e.g. "serve backend/index.php") or to
27+
# run a long-running PHP script as a worker process (e.g. "php worker.php").
28+
#
29+
# entrypoint: serve index.php

cloud_sql/mysql/pdo/index.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
/*
3+
* Copyright 2020 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
require_once 'src/DB.php';
19+
require_once 'src/Votes.php';
20+
21+
use Google\Cloud\Samples\CloudSQL\MySQL\DB;
22+
use Google\Cloud\Samples\CloudSQL\MySQL\Votes;
23+
24+
$votes = new Votes(DB::createPdoConnection());
25+
26+
if ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'GET') {
27+
$list = $votes->list();
28+
29+
$vote_count = $votes->count_candidates();
30+
$tab_count = $vote_count['tabs'];
31+
$space_count = $vote_count['spaces'];
32+
33+
include_once("./template.php");
34+
} elseif ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'POST') {
35+
$message = 'Invalid vote. Choose Between TABS and SPACES';
36+
37+
if (!empty($_POST['team']) && in_array($_POST['team'], ['SPACES', 'TABS'])) {
38+
$message = $votes->save($_POST['team']);
39+
}
40+
41+
echo $message;
42+
}

cloud_sql/mysql/pdo/src/DB.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2+
/*
3+
* Copyright 2020 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace Google\Cloud\Samples\CloudSQL\MySQL;
19+
20+
use PDO;
21+
22+
class DB
23+
{
24+
public static function createPdoConnection()
25+
{
26+
$username = getenv("DB_USER");
27+
$password = getenv("DB_PASS");
28+
$schema = getenv("DB_NAME");
29+
$hostname = getenv("DB_HOSTNAME") ?: "127.0.0.1";
30+
$cloud_sql_connection_name = getenv("CLOUD_SQL_CONNECTION_NAME");
31+
32+
// # [START cloud_sql_mysql_pdo_create]
33+
// // $username = 'your_db_user';
34+
// // $password = 'yoursupersecretpassword';
35+
// // $schema = 'your_db_name';
36+
// // $cloud_sql_connection_name = getenv("CLOUD_SQL_CONNECTION_NAME");
37+
38+
if ($cloud_sql_connection_name) {
39+
// Connect using UNIX sockets
40+
$dsn = sprintf(
41+
'mysql:dbname=%s;unix_socket=/cloudsql/%s',
42+
$schema,
43+
$cloud_sql_connection_name
44+
);
45+
} else {
46+
// Connect using TCP
47+
// $hostname = '127.0.0.1';
48+
$dsn = sprintf('mysql:dbname=%s;host=%s', $schema, $hostname);
49+
}
50+
51+
return new PDO($dsn, $username, $password);
52+
# [END cloud_sql_mysql_pdo_create]
53+
}
54+
}

cloud_sql/mysql/pdo/src/Votes.php

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
2+
/*
3+
* Copyright 2020 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace Google\Cloud\Samples\CloudSQL\MySQL;
19+
20+
use PDO;
21+
22+
class Votes
23+
{
24+
private $connection;
25+
26+
public function __construct(PDO $connection)
27+
{
28+
$this->connection = $connection;
29+
$this->create_table();
30+
}
31+
32+
private function create_table()
33+
{
34+
$sql = "CREATE TABLE IF NOT EXISTS votes (
35+
vote_id INT NOT NULL AUTO_INCREMENT,
36+
time_cast DATETIME NOT NULL,
37+
candidate VARCHAR(6) NOT NULL,
38+
PRIMARY KEY (vote_id)
39+
);";
40+
41+
$this->connection->exec($sql);
42+
}
43+
44+
public function list()
45+
{
46+
$sql = "SELECT candidate, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5";
47+
$statement = $this->connection->prepare($sql);
48+
$statement->execute();
49+
return $statement->fetchAll();
50+
}
51+
52+
public function count_candidates()
53+
{
54+
$sql = "SELECT COUNT(vote_id) as voteCount FROM votes WHERE candidate = ?";
55+
$count = [];
56+
57+
$statement = $this->connection->prepare($sql);
58+
59+
//tabs
60+
$statement->execute(['TABS']);
61+
$count['tabs'] = $statement->fetch()[0];
62+
63+
//spaces
64+
$statement->execute(['SPACES']);
65+
$count['spaces'] = $statement->fetch()[0];
66+
67+
return $count;
68+
}
69+
70+
public function save($team)
71+
{
72+
$sql = "INSERT INTO votes (time_cast, candidate) VALUES (NOW(), :candidate)";
73+
$statement = $this->connection->prepare($sql);
74+
$statement->bindParam('candidate', $team);
75+
76+
if ($statement->execute()) {
77+
return "Vote successfully cast for '$team'";
78+
}
79+
80+
return print_r($statement->errorInfo(), true);
81+
}
82+
}

cloud_sql/mysql/pdo/template.php

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
16+
17+
18+
Tabs VS Spaces
19+
20+
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
21+
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
32+

33+
if ($tab_count == $space_count): ?>
34+
TABS and SPACES are evenly matched!
35+
elseif ($tab_count > $space_count): ?>
36+
TABS are winning by $tab_count - $space_count?>
37+
$tab_count - $space_count > 1 ? "votes" : "vote" ?>!
38+
elseif ($space_count > $tab_count): ?>
39+
SPACES are winning by $space_count - $tab_count?>
40+
$space_count - $tab_count > 1 ? "votes" : "vote" ?>!
41+
endif ?>
42+
43+
44+
45+
46+
$tab_count > $space_count ?: 'green lighten-3' ?>">
47+
keyboard_tab
48+

$tab_count?> votes

49+
50+
51+
52+
53+
$tab_count < $space_count ?: 'blue lighten-3' ?>">
54+
space_bar
55+

$space_count?> votes

56+
57+
58+
59+
60+

Recent Votes

61+
    62+
    foreach ($list as $vote): ?>
    63+
  • 64+
    if ($vote['candidate'] == "TABS"): ?>
    65+
    keyboard_tab
    66+
    elseif ($vote['candidate'] == "SPACES"): ?>
    67+
    space_bar
    68+
    endif ?>
    69+
    70+
    A vote for $vote['candidate'] ?>
    71+
    72+

    was cast at $vote['time_cast'] ?>

    73+
    74+
    endforeach ?>
    75+
    76+
    77+
    98+
    99+

    0 commit comments

    Comments
     (0)