File tree Expand file tree Collapse file tree 2 files changed +30
-5
lines changed
Expand file tree Collapse file tree 2 files changed +30
-5
lines changed Original file line number Diff line number Diff line change 2020namespace Google \Cloud \Samples \CloudSQL \MySQL ;
2121
2222use 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}
Original file line number Diff line number Diff line change 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 (
9096 );
9197 }
9298
93- $ conn ->setAttribute (PDO ::ATTR_ERRMODE , PDO ::ERRMODE_EXCEPTION );
9499 return $ conn ;
95100};
96101
You can’t perform that action at this time.
0 commit comments