Last active
August 29, 2015 14:23
-
-
Save ahhh/38093a7a2593a4df641c to your computer and use it in GitHub Desktop.
PDO prepared statement example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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