PDO查询问题
我正在将一些代码从旧的 mysql_* 函数更新为 PDO。 它连接没有问题,运行查询也没有问题,但结果集是空的。 PDO::query() 应该返回一个 PDOStatement 对象,但我得到了 true 作为回报。 没有报告错误。
这是我的代码:
try
{
$DB = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
$stmt = $DB->prepare("SELECT * FROM report_clientinfo");
$stmt->execute();
}catch(PDOException $e)
{
echo $e->getMessage() . "\n";
}
echo gettype($stmt) . "\n";
if ($stmt) echo "true\n";
else echo "false\n";
$resultset = $stmt->fetchAll();
if(empty($resultset))
{
exit("ERROR: getClientInfo query failed.");
}
$DB = null;
print_r($resultset);
我看到的输出是:
object 真的 错误:getClientInfo 查询失败。
有什么想法为什么它不返回任何结果吗?
I am updating some code from the old mysql_* functions to PDO. It connects without a problem, runs the query without a problem, but the resultset is empty. PDO::query() is supposed to return a PDOStatement object, yet I am getting true in return. No errors are reported.
Here is my code:
try
{
$DB = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
$stmt = $DB->prepare("SELECT * FROM report_clientinfo");
$stmt->execute();
}catch(PDOException $e)
{
echo $e->getMessage() . "\n";
}
echo gettype($stmt) . "\n";
if ($stmt) echo "true\n";
else echo "false\n";
$resultset = $stmt->fetchAll();
if(empty($resultset))
{
exit("ERROR: getClientInfo query failed.");
}
$DB = null;
print_r($resultset);
The output I am seeing is:
object
true
ERROR: getClientInfo query failed.
Any ideas why it is not returning any results?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,您的
PDOStatement $stmt
变量实际上被报告为一个对象,而不是“true
”。 然后,当代码发现$stmt
为非空时,它会打印“true
”(事实确实如此,因为它是一个对象)。我建议您检查
$stmt->execute()
的返回值。 您可能遇到 SQL 错误。 例如,如果您拼写错误表名称,或者您连接的数据库“dbname
”中不存在该表,或者您登录的用户没有查询该表的权限。另请检查
$stmt->errorInfo()
获取有关发生的任何错误的更多详细信息。It looks to me like your
PDOStatement $stmt
variable is in fact reported to be an object, not "true
". The code then prints "true
" when it sees that$stmt
is non-null, which it is, because it's an object.I recommend that you check the return value from
$stmt->execute()
. You might have an SQL error. For example, if you misspelled the table name, or the table doesn't exist in the database "dbname
" that you connected to, or the user you login as doesn't have privilege to query that table.Also check
$stmt->errorInfo()
to get more details on any error that occurred.我有点尴尬地报告说我指向了错误的 DSN。 我想这就是我在除夕夜外出后尝试在几个小时的睡眠中学习新东西所得到的结果。 感谢您对 PDOStatement::errorInfo() 方法的提示,我以前没有注意到它。
I'm a little embarrassed to report back that I was pointing to the wrong DSN. I guess that's what I get for trying to learn something new on just a few hours of sleep after going out for New Year's Eve. Thanks for the tip on the PDOStatement::errorInfo() method, I had not noticed it before.