PDO Prepared Statements

Precompiled SQL statement that uses the prepare() PDO method that is then executed by the execute() method.


Line 10 shows an SQL query being assigned to a variable which is then assigned to the $statement variable using the prepare() method on line 13. The prepared statement is then executed on line 16:

	ini_set('display_errors', '0');

	$team = 'Honda';
	$status = 'Factory';

	//assign the query to a variable
	$sqlQuery = "SELECT * from riders where team = '$team' AND status = '$status'";

	//now use the prepare() method & assign to $statement to create a prepared statement
	$statement = $dbh->prepare($sqlQuery);

	catch(PDOException $error){
		echo errorHandling($error);
	while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
		echo $row['name'] . " rides a " . $row['team'] . " " . $row['status'] . " MotoGP bike!<br>";

Save & refresh browser:

Connected to the motogp database
Dani Pedrosa rides a Honda Factory MotoGP bike!
Marc Marquez rides a Honda Factory MotoGP bike!
Stefan Bradl rides a Honda Factory MotoGP bike!
Alvaro Bautista rides a Honda Factory MotoGP bike!


*note: the fetch() method is now being used in the while loop on line 21, in place of our previous query() method in the foreach loop

Leave a Reply