PHP PDO for Dummies
mysql, pdo, php, sql
Solution
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();
}
Problem
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.