4

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

}
Stephen S
  • 166
  • 1
  • 1
  • 12
  • 2
    It's great that you're using PDO, but please, **DO NOT** inject strings directly into your query. Always use [SQL placeholders](http://www.phpeveryday.com/articles/PDO-Positional-and-Named-Placeholders-P551.html) to do this for you safely and correctly. – tadman Oct 25 '12 at 18:36
  • The `$dbsite` variable is not front-end user accessible....It's strictly a config.php constant. I'm currently working on extending the PDO class so that I do not have to append the DB name to a query. I already know that injecting strings directly is bad. I was actually just researching if prepared statements actually escape values or not. – Stephen S Oct 25 '12 at 19:49

1 Answers1

27

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]);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sammitch
  • 30,782
  • 7
  • 50
  • 77