如何在 PDO PHP 中查看查询错误 [英] How to view query error in PDO PHP

查看:29
本文介绍了如何在 PDO PHP 中查看查询错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try {
    $db = new PDO("mysql:host=".HOST.";dbname=".DB, USER, PW);
    $st = $db->prepare("SELECT * FROM c6ode");
}
catch (PDOException $e){
    echo $e->getMessage();
}

在上述情况下,如何检查查询的 mysql 错误?

How can I check the mysql error for the query in above case?

推荐答案

需要将错误模式属性PDO::ATTR_ERRMODE设置为PDO::ERRMODE_EXCEPTION.
由于您希望 prepare() 方法抛出异常,您应该禁用 PDO::ATTR_EMULATE_PREPARES* 功能.否则 MySQL 服务器不会看到"语句,直到它被执行.

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

打印(就我而言)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

http://wezfurlong.org/blog/2006/apr/使用-pdo-mysql/
EMULATE_PREPARES=true 现在似乎是 pdo_mysql 驱动程序的默认设置.从那时起,查询缓存的内容已得到修复/更改,并且使用 mysqlnd 驱动程序我没有遇到 EMULATE_PREPARES=false 问题(虽然我只是一个 php 爱好者,请不要相信我的话......)

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) 然后是 PDO::MYSQL_ATTR_DIRECT_QUERY - 我必须承认我不理解这两个属性的交互(还没有?),所以我设置了它们,就像

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

这篇关于如何在 PDO PHP 中查看查询错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆