PDO::Query() returning false

Stephen S picture Stephen S · Oct 25, 2012 · Viewed 16.8k times · Source

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';

}

Answer

Sammitch picture Sammitch · Oct 25, 2012

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