Skip to content

Instantly share code, notes, and snippets.

@ahhh
Last active August 29, 2015 14:23
Show Gist options
  • Save ahhh/38093a7a2593a4df641c to your computer and use it in GitHub Desktop.
Save ahhh/38093a7a2593a4df641c to your computer and use it in GitHub Desktop.
PDO prepared statement example
<?php
// Step 1: Establish a connection
$db = new PDO("mysql:host=localhost;dbname=testdb", "user", "secretpass");
// Step 2: Construct your prepared statement, note the ? for our input
$query = $db->prepare("SELECT * FROM foo WHERE bar = :zip");
// Step 3: bind our paramters to the query
$query->bindParam(':zip', $zip);
// Step 4: execute the query
$query->execute();
// Step 5: Iterate over the results
while($row = $query->fetch()) {
print_r($row);
}
// Optional Step: Re-assign variables in prepared statement
//$zip = 'new_value';
//$query->execute();
// Final Step: Free used resources
$query->closeCursor();
$db = null;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment