使用PDO插入。我应该用try ... catch吗?

时间:2014-01-07 00:09:55

标签: php mysql pdo

我刚刚开始使用PDO,我有这个代码在我的表中插入值。

$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$sql = "INSERT INTO lists (ID, Title, Timestamp, Plays, Likes) 
VALUES (:ID, :Title, :Timestamp, :Plays, :Likes)";
$q = $dbh->prepare($sql);
$q->execute(array(':ID'=>$list[$i]["id"],
              ':Title'=>$list[$i]["title"],
              ':Timestamp'=>$list[$i]["timestamp"],
              ':Plays'=>$list[$i]["playcount"],
              ':Likes'=>$list[$i]["likes"]));

从阅读论坛,我明白有时我会需要使用try ... catch出于安全原因。我真的很困惑...在我的情况下,我应该改变什么才能使用试试.. .catch ???

非常感谢!

1 个答案:

答案 0 :(得分:0)

很抱歉删除,在帖子完成之前意外点击了帖子。以下是使用PDO时实现错误报告的一种方法:

try {
if($dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password)) {
// Set Errorhandling to Exception instead of PDO error reporting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} else {
  throw new Exception(": Connection Error ");
}
...later in code block
$sql = "INSERT INTO lists (ID, Title, Timestamp, Plays, Likes) 
VALUES (:ID, :Title, :Timestamp, :Plays, :Likes)";

if($q = $dbh->prepare($sql)) {
$q->execute(array(':ID'=>$list[$i]["id"],
          ':Title'=>$list[$i]["title"],
          ':Timestamp'=>$list[$i]["timestamp"],
          ':Plays'=>$list[$i]["playcount"],
          ':Likes'=>$list[$i]["likes"]));
}else {
 throw new Exception(“: Error on Insert “);
}
//now catch all throw errors
} catch(Exception $e){
$mes = $date.": bdh errors ";
$mes .= $e->getMessage();
//send errors to system error reporting
error_log($mes);
}

有关PDO错误驱动程序的详细信息,请查看PDO Exceptions