简体   繁体   中英

What's wrong with my PDO syntax? Is it possible to get a clearer error report?

I'm just trying to do a simple insert:

$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';
}

But it's failing. Can someone tell me why? And even better, is it possible to get a more helpful return value from the execute() method than simply true or false?

But it's failing. Can someone tell me why?

Hard to say. Should those values be quoted? The error thrown by MySQL would be useful to diagnose the problem. Which leads me to...

And even better, is it possible to get a more helpful return value from the execute() method than simply true or false?

So long as PDO is set up to throw exceptions on errors...

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

...wrap it in a try / catch block and examine the exception thrown.

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

By default, PDO's error mode is ERRMODE_SILENT so it won't complain if anything goes wrong. To see real errors, either set it to ERRMODE_WARNING or ERRMODE_EXCEPTION to throw exceptions. 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();
}

With something like this you will be able to get the error.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM