William Entriken
William Entriken

Reputation: 39333

PHP PDO for Dummies

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.

Upvotes: 10

Views: 9591

Answers (2)

Dean Rather
Dean Rather

Reputation: 32404

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();
}

Upvotes: 15

goat
goat

Reputation: 31854

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);

Upvotes: 3

Related Questions