2

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.

Community
  • 1
  • 1
matt
  • 777
  • 2
  • 12
  • 25
  • @Skrol29 According to [the docs](http://php.net/manual/en/pdostatement.bindparam.php), matt's doing that right. – SomeKittens Oct 26 '12 at 14:42

1 Answers1

1

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);
bcmcfc
  • 25,966
  • 29
  • 109
  • 181
  • you sir, deserve a warm shake by the hand. I knew this was a schoolboy error on my part. Great job! – matt Oct 26 '12 at 14:45
  • @matt No problem - I suspect the confusion arose from the answer to your other question, where the answerer uses `query` instead of `prepare`, and thus didn't call `execute`. – bcmcfc Oct 26 '12 at 14:46
  • what is the difference between using prepare or query in this specific case? is there a better practice? – matt Oct 26 '12 at 14:47
  • There's some more stuff on `query` and `prepare` here: http://stackoverflow.com/questions/4700623/pdos-query-vs-execute and http://stackoverflow.com/questions/4978481/pdoexec-or-pdoquery – bcmcfc Oct 26 '12 at 14:47