File tree 2 files changed +30
-5
lines changed
2 files changed +30
-5
lines changed Original file line number Diff line number Diff line change 20
20
namespace Google \Cloud \Samples \CloudSQL \MySQL ;
21
21
22
22
use PDO ;
23
+ use PDOException ;
24
+ use RuntimeException ;
23
25
24
26
/**
25
27
* Manage votes using the Cloud SQL database.
@@ -94,10 +96,28 @@ public function getCountByValue(string $value) : int
94
96
*/
95
97
public function insertVote (string $ value ) : bool
96
98
{
99
+ $ conn = $ this ->connection ;
100
+ $ res = false ;
101
+
102
+ # [START cloud_sql_mysql_pdo_connection]
103
+ // Use prepared statements to guard against SQL injection.
97
104
$ sql = "INSERT INTO votes (time_cast, vote_value) VALUES (NOW(), :voteValue) " ;
98
- $ statement = $ this ->connection ->prepare ($ sql );
99
- $ statement ->bindParam ('voteValue ' , $ value );
100
105
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 ;
102
122
}
103
123
}
Original file line number Diff line number Diff line change 61
61
$ dsn = sprintf ('mysql:dbname=%s;host=%s ' , $ dbName , $ hostname );
62
62
}
63
63
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
+ ]);
65
71
# [END cloud_sql_mysql_pdo_create]
66
72
} catch (TypeError $ e ) {
67
73
throw new RuntimeException (
90
96
);
91
97
}
92
98
93
- $ conn ->setAttribute (PDO ::ATTR_ERRMODE , PDO ::ERRMODE_EXCEPTION );
94
99
return $ conn ;
95
100
};
96
101
You can’t perform that action at this time.
0 commit comments