我的PDO语法出了什么问题?是否有可能获得更清晰的错误报告?

时间:2012-02-16 01:36:48

标签: php mysql pdo

我只是想做一个简单的插入:

$dbh = new PDO("mysql:host=" . WEBSITE_SERVER . "; dbname=fluenz_website", WEBSITE_LOGIN,   WEBSITE_PW);
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");

if($query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))){
    echo 'PDO SUCCESS';
}else{
    echo 'PDO FAILURE';
}

但它失败了。有人可以告诉我为什么吗?更好的是,是否可以从execute()方法获得更有用的返回值,而不仅仅是真或假?

3 个答案:

答案 0 :(得分:2)

  

但它失败了。有人可以告诉我为什么吗?

很难说。这些价值应该被引用吗? MySQL抛出的错误对于诊断问题很有用。这导致我...

  

更好的是,是否可以从execute()方法获得更有用的返回值,而不仅仅是true或false?

只要PDO设置为在错误上抛出异常......

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

...将其包装在try / catch块中,并检查抛出的异常。

try {    
    $query->execute(...);
} catch (PDOException $e) {
    echo $e->getMessage();
}

答案 1 :(得分:1)

默认情况下,PDO的错误模式为ERRMODE_SILENT,因此如果出现任何问题,它不会抱怨。要查看真实错误,请将其设置为ERRMODE_WARNINGERRMODE_EXCEPTION以抛出异常。 http://php.net/manual/en/pdo.error-handling.php

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

try {
  $query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
  $query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))
}
catch (PDOException $e) {
  echo "Query failed: " $e->getMessage();
}

答案 2 :(得分:0)

通过这样的方式,您将能够得到错误。

$dbh = new PDO("mysql:host=" . WEBSITE_SERVER . "; dbname=fluenz_website", WEBSITE_LOGIN,   WEBSITE_PW);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");

    try {
        if($query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))){
        echo 'PDO SUCCESS';
        }else{
            echo 'PDO FAILURE';
        }
    } 
    catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }