matt
matt

Reputation: 787

PDO prepared query returns nothing

This is a followup from a previous question: When to use PDO prepared queries. mysql_real_escape error

Im a total beginner and was using mysql_real_escape on each GET and POST variable before i queried my DB. When i came to upload to my host, i realised that you shouldnt use this with PDO. Im in the process of changing all queries with user submitted data to prepared queries.

I connect to my DB like this:

$hostname = "localhost";
$username = "root";
$password = "root";

try {
     $dbh = new PDO("mysql:host=$hostname;dbname=wmpt", $username, $password);

}
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

below is an example query:

$url = $_GET['q'];
$STH = $dbh->prepare("SELECT qid FROM tblurl WHERE url = :url");
$STH->bindParam(':url', $url);
$STH->setFetchMode(PDO::FETCH_ASSOC);  
$urlid = $STH->fetch();
print_r($urlid);

the print_r outputs absolutely nothing, i'm testing my GET variable with test values right from the DB. Any ideas what I'm doing wrong? I'm sure i'm being an idiot, help is very much appreciated.

Upvotes: 2

Views: 159

Answers (1)

bcmcfc
bcmcfc

Reputation: 26825

You just need to execute your query before you can fetch results.

$url = $_GET['q'];
$STH = $dbh->prepare("SELECT qid FROM tblurl WHERE url = :url");
$STH->bindParam(':url', $url);

$STH->execute();

$STH->setFetchMode(PDO::FETCH_ASSOC);  
$urlid = $STH->fetch();
print_r($urlid);

Upvotes: 1

Related Questions