PHP错误检查PDO准备语句

时间:2014-01-23 13:06:23

标签: php mysql pdo

我的代码是:

//insert a new record
$sSQL="INSERT INTO store_content_charity (store_id, description, dateaddedserial, approvalstatus) VALUES (:store_id, :description, :dateaddedserial, 0) ";
$objQuery=$objConn->prepare($sSQL);
if (false===$objQuery)
    echo 'prepare() failed: ' . $objConn->error . '<br/>';

if (!$objQuery->bindParam(':store_id', $_SESSION['StoreLoggedIn_ID']))
    echo "Binding parameters failed: (" . $objQuery->errno . ") " . $objQuery->error . '<br/>';
if (!$objQuery->bindParam(':description', trim($_POST["txtDescription"])))
    echo "Binding parameters failed: (" . $objQuery->errno . ") " . $objQuery->error . '<br/>';
if (!$objQuery->bindParam(':dateaddedserial', date("YmdHis")))
    echo "Binding parameters failed: (" . $objQuery->errno . ") " . $objQuery->error . '<br/>';

if (!$objQuery->execute())
    echo "Execute failed: (" . $objQuery->errno . ") " . $objQuery->error . '<br/>';

导入失败,消息“执行失败:()” - 就是这样......没有号码或消息。

  1. 有谁知道为什么会失败?
  2. 为什么我没有收到错误消息,告诉我它失败的原因?
  3. 奇怪的是,如果我删除bindParam并硬编码数据,我知道这段代码确实有用......

    一如既往地感谢您的建议......

    编辑: 我添加了Mike B建议的线路&amp;甚至用try / catch包围它:

    try {
        $objConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    

    但这只会导致脚本在此行没有任何消息而失败......

1 个答案:

答案 0 :(得分:0)

感谢Mike B&amp; ChrisForrence ....

一旦我把一切都包围在try-catch中,我就能看到错误&amp;能够解决它。

(错误是该文件被编码为没有BOM的UTF-8,我试图添加的文本包括£符号 - 当我编码为UTF-8时,一切都按预期工作!)

我想我可以将代码修改为:

$objConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $sSQL="INSERT INTO store_content_charity (store_id, description, dateaddedserial, approvalstatus) VALUES (:store_id, :description, :dateaddedserial, 0) ";
    $objQuery=$objConn->prepare($sSQL);
    $objQuery->bindParam(':store_id', $_SESSION['StoreLoggedIn_ID']);
    $objQuery->bindParam(':description', trim($_POST["txtDescription"]));
    $objQuery->bindParam(':dateaddedserial', date("YmdHis"));
    $objQuery->execute();
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}