user1391838
user1391838

Reputation:

PDO Query Won't Work

I can't for the life of my figure out why this is not working. I have a different area of the website which uses almost exactly the same code as this and it works just fine. I'm sure it's something obvious, but I'm pretty new to this stuff. There is no error or anything; it just does nothing. The $name variable works fine (I've tested it), and the database is up to date.

try {
     $db = new PDO($dbhost, $dbuser, $dbpassword);
     $statement = $db->prepare("select first, last from users where email = $name");
     $result = $statement->fetch();
     $first = $result[first];
     $last = $result[last];
}catch(PDOException $e) {
     echo $e->getMessage();
}

Upvotes: 0

Views: 145

Answers (2)

bugwheels94
bugwheels94

Reputation: 31920

you have to use execute()

try {
$db = new PDO($dbhost, $dbuser, $dbpassword);
$statement = $db->prepare("select first, last from users where email = ?");
$statement->execute(array($name));
$result = $statement->fetch();
$first = $result[first];
$last = $result[last];}

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

Upvotes: 1

cdhowie
cdhowie

Reputation: 169018

You can't fetch rows before you actually execute the query; you have only prepared the query. The ultimate problem is that you lack a call to $statement->execute(). The proper PDO idiom is something like this:

$statement = $db->prepare("select first, last from users where email = ?");
if (!$statement->execute(array($name))) {
    // Handle error
}
$result = $statement->fetch();
$statement->closeCursor();

Don't forget the closeCursor() call when you are finished fetching rows. On some database systems that don't support concurrent queries by the same client, not calling this function may cause the next query to fail to execute.

Upvotes: 0

Related Questions