我正在寻找一个PHP PDO的完整工作示例,包括最佳实践来运行查询和处理错误。以下是我目前的进展。
连接。如果您不这样做,连接失败将默认向您网站的所有用户公开数据库凭据。
try {
$dbh = new PDO("mysql:host=localhost;dbname=phor_lang", "phor_lang", "'9lsnthsn9");
} catch (PDOException $e) {
error(false, "PDO ERROR: " . $e->getMessage());
}
查询
$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();
然而,这导致查询失败(执行返回false),并且错误消息为空白。