简体   繁体   中英

Using a PDO COUNT query with parameters

I have the following PDO query set up:

$CHECK_MATCH = $DBH->query("
    SELECT COUNT(*) as matches FROM users WHERE 
        username = :username AND password = :password
");
$CHECK_MATCH->bindParam(':username', $username);
$CHECK_MATCH->bindParam(':password', $password);

However, I recieve an error saying:

Fatal error: Call to a member function bindParam() on a non-object

Why doesn't this work?
How would I retrieve the required values from the statement if i used prepare instead of query ?

You didn't prepare a statement. You DIRECTLY executed a query. Since a placeholder-using query is NOT a valid query as far as ->query() is concerned, the query failed, and returned a boolean FALSE. You then took that boolean FALSE and tried to treat it as an object.

The proper sequence is:

$stmt = $dbh->prepare('.... your query here ...');
              ^^^^^^^----note the new method call
$stmt->bindParam(...);

$stmt->execute();

I think this answer is not necessary because Marc B 's answer actually solve the prob. Well, since @proPhet requested for a complete solution, here it is:

$CHECK_MATCH = $DBH->prepare("SELECT COUNT(*) as matches FROM users WHERE 
    username = :username AND password = :password");
$CHECK_MATCH->bindParam(':username', $username);
$CHECK_MATCH->bindParam(':password', $password);

$CHECK_MATCH->execute();
// Fetch as object
$row = $CHECK_MATCH->fetch(PDO::FETCH_OBJ);

echo $row->matches;

You need to prepare the query:

$CHECK_MATCH = $DBH->prepare("  <------ Changed query for prepare
    SELECT COUNT(*) as matches FROM users WHERE 
        username = :username AND password = :password
");
$CHECK_MATCH->bindParam(':username', $username);
$CHECK_MATCH->bindParam(':password', $password);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM