1

I am calling a mysql stored procedure using PDO in PHP

try {

    $conn = new PDO("mysql:host=$host_db; dbname=$name_db", $user_db, $pass_db);    
    $stmt = $conn->prepare('CALL sp_user(?,?,@user_id,@product_id)');    
    $stmt->execute(array("user2", "product2"));    
    $stmt->setFetchMode(PDO::FETCH_COLUMN, 0);
    $errors = $stmt->errorInfo();
    if($errors){
        echo $errors[2];
    }else{
        /*Do rest*/
    }

}catch(PDOException $e) {
  echo "Error : ".$e->getMessage();
}

that return below error because the name of the field in insert query was given wrong

Unknown column 'name1' in 'field list'

So i want to know if this is possible to get detailed error information something like:-

Unknown column 'Tablename.name1' in the 'field list';

that could tell me what column of which table is Unknown.

4

2 回答 2

0

在创建 pdo 连接时,传递错误模式和编码等选项: PDO 系统由 3 个类组成:PDO、PDOStatement 和 PDOException。PDOException类是您进行错误处理所需要的。

这是一个例子:

try
{
    // use the appropriate values …
    $pdo = new PDO($dsn, $login, $password);
    // any occurring errors wil be thrown as PDOException
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $ps = $pdo->prepare("SELECT `name` FROM `fruits` WHERE `type` = ?");
    $ps->bindValue(1, $_GET['type']);
    $ps->execute();
    $ps->setFetchMode(PDO::FETCH_COLUMN, 0);
    $text = "";
    foreach ($ps as $row)
    {
         $text .= $row . "<br>";
    }
    // a function or method would use a return instead
    echo $text;
} catch (Exception $e) {
    // apologise
    echo '<p class="error">Oops, we have encountered a problem, but we will deal with it. Promised.</p>';
    // notify admin
    send_error_mail($e->getMessage());
}
// any code that follows here will be executed
于 2013-01-08T17:50:33.253 回答
0

我发现这对我很有帮助。“error_log”打印到 php 错误日志,但您可以用任何您想显示错误的方式替换。

} catch (PDOException $ex){
    error_log("MYSQL_ERROR"); //This reminds me what kind of error this actually is
    error_log($ex->getTraceAsString()); // will show the php file line (and parameter 
                                        // values) so you can figure out which
                                        // query/values caused it
    error_log($ex->getMessage());  // will show the actual MYSQL query error 
                                   // e.g. constraint issue
}

ps 我知道这有点晚了,但也许它可以帮助某人。

于 2014-09-02T05:33:30.027 回答