I am looking for a PHP PDO full working example with best practices for running a query and handling errors. Here's what I have so far.
CONNECTING. If you don't do it this way, a connection failure will by default expose DB credentials to all users of your site.
try {
$dbh = new PDO("mysql:host=localhost;dbname=phor_lang", "phor_lang", "'9lsnthsn9");
} catch (PDOException $e) {
error(false, "PDO ERROR: " . $e->getMessage());
}
QUERYING
$stmt = $dbh->prepare("INSERT INTO sets");
$stmt->execute()
or error(0, "USERS ERROR ".__LINE__." ".print_r($dbh->errorInfo(),true));
$setID = $dbh->lastInsertID();
$stmt->closeCursor();
$stmt = $dbh->prepare("INSERT INTO words (language, name, detail, user, type, set) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute(array($l1l, $l1w, $l1d, $userID, 'training', $setID))
or error(0, "USERS ERROR ".__LINE__." ".print_r($dbh->errorInfo(),true));
$stmt->closeCursor();
However, this is resulting in queries that fail (execute returns false) and the error message is blank.
PDO in PHP (PHP Data Objects) is a lightweight, consistent framework for accessing databases in PHP. Database-specific features may be exposed as standard extension functions by any database driver that implements the PDO interface.
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way to access databases. This means developers can write portable code much easier. PDO is not an abstraction layer like PearDB.
PDO (PHP Data Objects) Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.
The main advantage of PDO over MySQLi is in the database support. PDO supports 12 different database types, in opposition to MySQLi, which supports MySQL only. When you have to switch your project to use another database, PDO makes the process simpler.
Here's a modern starter's guide to PDO. It answers some of your questions and explains a lot of other basic PDO functionality.
I just read over it yesterday and found it an excellent resource!
Here's a quote under 'errors':
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
By default, pdo doesnt throw exceptions upon errors.
you need to do configure it to
$dbh = new PDO("...", "...", "...", array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// or
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With