[英]PDO::Query() returning false
I'm attempting to learn and use PDO in PHP. 我正在尝试在PHP中学习和使用PDO。 I've come across an issue in the query() method.
我在query()方法中遇到了一个问题。
I'm attempting to use $sth = $db->query("SELECT * FROM titles ORDER BY RAND() LIMIT 1");
我正在尝试使用
$sth = $db->query("SELECT * FROM titles ORDER BY RAND() LIMIT 1");
to randomly select a title for a website, but for some reason, $sth
is always false. 随机选择一个网站的标题,但由于某种原因,
$sth
总是假的。 It works when I use prepare()
and execute()
, but I'm trying to find what's wrong in query()
. 它在我使用
prepare()
和execute()
,但我试图找到query()
的错误。
Here's my entire function that is being called: 这是我正在调用的整个函数:
function getTitle($db)
{
if($db)
{
$db->exec("USE " . $dbsite);
$sth = $db->query("SELECT * FROM titles ORDER BY RAND() LIMIT 1");
$title = $sth->fetch(PDO::FETCH_ASSOC);
$db->exec("UPDATE titles SET count = count + 1 WHERE id = " . $title['id']);
return $title['title'];
}
else
return 'Home - Database Offline';
}
Use PDO's errorinfo()
function to find out why. 使用PDO的
errorinfo()
函数找出原因。
if( ! $sth = $db->query("SELECT * FROM titles ORDER BY RAND() LIMIT 1") ) {
die(var_export($db->errorinfo(), TRUE));
}
Late Update 晚更新
In the interest of making my old answers better, setting PDO to throw exceptions on error is far more manageable than checking every function return. 为了使我的旧答案更好,设置PDO以在错误上抛出异常比检查每个函数返回更容易管理。
$dbh = new PDO($connstr, $user, $pwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Or, more concisely: 或者,更简洁:
$dbh = new PDO($connstr, $user, $pwd, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.