Last active
October 1, 2015 12:48
-
-
Save patrick-hertling/06d3a50eb6eeae0f22ed to your computer and use it in GitHub Desktop.
PDO Quickstart Guide
This file contains 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 | |
/** | |
* Quickstart: | |
* The following sequence should only give an idea of how to use PDO | |
* DON'T USE THIS CODE FOR A REAL SCENARIO! | |
*/ | |
$dsn = 'mysql:dbname=name_of_your_table'; // Define 'data source name' | |
$user = 'username'; // Define username | |
$pass = 'secret'; // Defeine password | |
$pdo = new PDO($dsn, $user, $pass); // Create the PDO object | |
// 1) Query the DB directly | |
$statement = $pdo->query("select * from test_table where id in '(1, 2, 3, 4)'"); | |
$result = $statement->fetchObject(); // This would fetch the first row into a stdClass object. | |
// 2) Using prepared statements: | |
// Using '?' as placeholders | |
$statement = $pdo->prepare('select * from test_table where name = ? and surname = ?'); | |
$statement->execute(array('Patrick', 'Hertling')); | |
$result = $statement->fetch(PDO::FETCH_ASSOC); // This would fetch the first row into an associative array. | |
// Using ':parameter' as placeholder | |
$statement = $pdo->prepare('select * from test_table where name = :name and surname = :surname'); | |
$statement->execute(array('name' => 'Patrick', 'surname' => 'Hertling')); | |
$result = $statement->fetchAll(); // This would fetch all the results into an array of associative arrays. | |
/** | |
* DOING IT RIGHT: | |
* Once you have the basic idea, check out a detailed tutorial | |
* http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers | |
* and the official PHP Manual. | |
* http://php.net/manual/en/class.pdo.php | |
* | |
* FEEL FREE TO USE THIS CODE | |
* Define the charset and the options when crating the PDO object. | |
* - Errors performing your queries generate exceptions | |
* - Deactivate the prepare emulation | |
*/ | |
$options = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); | |
$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password', $options); | |
$stmt = $pdo->prepare('select * from test_table where property = ?'); // Prepare Statement | |
$stmt->execute(['content']); // Execute the query | |
$result = $stmt->fetchObject(); // Fetch the first row of the result | |
// Looping through the result set | |
$stmt = $pdo->prepare('select * from test_table where property = ?'); // Prepare Statement | |
$stmt->execute(['content']); // Execute the query | |
foreach($stmt as $row) { | |
// Do something with the result $row | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment