Skip to content

Commit cfee1a5

Browse files
committed
address review
1 parent dd1680d commit cfee1a5

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

cloud_sql/mysql/pdo/src/Votes.php

+23-3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
namespace Google\Cloud\Samples\CloudSQL\MySQL;
2121

2222
use PDO;
23+
use PDOException;
24+
use RuntimeException;
2325

2426
/**
2527
* Manage votes using the Cloud SQL database.
@@ -94,10 +96,28 @@ public function getCountByValue(string $value) : int
9496
*/
9597
public function insertVote(string $value) : bool
9698
{
99+
$conn = $this->connection;
100+
$res = false;
101+
102+
# [START cloud_sql_mysql_pdo_connection]
103+
// Use prepared statements to guard against SQL injection.
97104
$sql = "INSERT INTO votes (time_cast, vote_value) VALUES (NOW(), :voteValue)";
98-
$statement = $this->connection->prepare($sql);
99-
$statement->bindParam('voteValue', $value);
100105

101-
return $statement->execute();
106+
try {
107+
$statement = $conn->prepare($sql);
108+
$statement->bindParam('voteValue', $value);
109+
110+
$res = $statement->execute();
111+
} catch (PDOException $e) {
112+
throw new RuntimeException(
113+
"Could not insert vote into database. The PDO exception was " .
114+
$e->getMessage(),
115+
$e->getCode(),
116+
$e
117+
);
118+
}
119+
# [END cloud_sql_mysql_pdo_connection]
120+
121+
return $res;
102122
}
103123
}

cloud_sql/mysql/pdo/src/app.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,13 @@
6161
$dsn = sprintf('mysql:dbname=%s;host=%s', $dbName, $hostname);
6262
}
6363

64-
$conn = new PDO($dsn, $username, $password);
64+
// Connect to the database.
65+
// Here we set the connection timeout to five seconds and ask PDO to
66+
// throw an exception if any errors occur.
67+
$conn = new PDO($dsn, $username, $password, [
68+
PDO::ATTR_TIMEOUT => 5,
69+
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
70+
]);
6571
# [END cloud_sql_mysql_pdo_create]
6672
} catch (TypeError $e) {
6773
throw new RuntimeException(
@@ -90,7 +96,6 @@
9096
);
9197
}
9298

93-
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
9499
return $conn;
95100
};
96101

0 commit comments

Comments
 (0)