0

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?

4
  • 1
    Why don't you enable PDO warnings? ->query is meant for direct execution, not statement preparation. Commented Sep 9, 2014 at 16:27
  • 1
    Try $DBH->prepare instead of $DBH->query Commented Sep 9, 2014 at 16:29
  • I used ->query so that I could grab values from the results. How would I get those values using a prepared statement? Commented Sep 9, 2014 at 16:29
  • 1
    You can get those values using $row = $CHECK_MATCH->fetch(PDO::FETCH_OBJ) Commented Sep 9, 2014 at 16:31

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.