"A native mechanism for connecting to databases called PHP data objects, or PDO for short"
Also know as a prepared statement, a PDO provides methods for working with databases, including MySQL databases. Their main asset is to execute the same or similar database statements repeatedly with high efficiency.
Benefits of using PDO's:
- Access a wide range of DB's
- Use of exceptions for error handling
- The overhead of compiling and optimising the statement is incurred only once, although the statement can be executed multiple times.
- PDO's offer protection against malicious SQL injection attacks
// This creates an object of the PDO class
$db = new PDO("mysql:host=localhost;dbname=shane;port=????", "USERNAME", "PASS");
Example
try {
// Create object that can connect to the DB
$db = new PDO("mysql:host=localhost;dbname=shane;port=0000", "USERNAME", "PASS");
// Throw exceptions when there's an error in the query
$bd->setAttribute(PDO::ARRT_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Define the character set
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Error connecting to DB";
exit;
}
try {
// Using the query method on the PDO to get data
$results = $db->query("SELECT whatever, whatever2 FROM wherever ORDER BY sku ASC");
} catch(Exception $e) {
echo "Error retrieving data";
exit;
}
var_dump($results->fetchAll(PDO::FETCH_ASSOC));
References
PDO Vs. MySQLi: Which should you use? - Envatotuts+