PDO::Query() returning false

旧城冷巷雨未停 提交于 2020-01-02 10:17:43

问题


I'm attempting to learn and use PDO in PHP. I've come across an issue in the query() method.

I'm attempting to use $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. It works when I use prepare() and execute(), but I'm trying to find what's wrong in 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';

}

回答1:


Use PDO's errorinfo() function to find out why.

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.

$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]);


来源:https://stackoverflow.com/questions/13074492/pdoquery-returning-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!