Error in PDO page Call to a member function bindValue() on a non-object

user2936176 picture user2936176 · Oct 30, 2013 · Viewed 14.8k times · Source

I am very new to PDO.

I tried making a login page to my website and the code is shown below

<?php
     if(isset($_POST['username'])and isset($_POST['password']))
     { 

session_start();
$db = new PDO('mysql:host=localhost;dbname=hydra', 'root', '');

$username = $_POST['username'];
$password = $_POST['password'];

$query = $db->query("SELECT * FROM login where username=:username AND password=:password");
    $query->bindValue(":username", $username, PDO::PARAM_STR);
    $query->bindValue(":password", $password, PDO::PARAM_STR);
    $query->execute();

    if($query->rowcount() >0 )
    {
        echo "No Records Found!";
        header('Location: login.php');
    }
    else
    {
        $_SESSION['username'] = $_POST['username'];
        header("Location: home.php");

    }




           }
         ?>

after trying to login, I got this following error : Call to a member function bindValue() on a non-object

Whats wrong with my code?

Answer

Hecke29 picture Hecke29 · Oct 30, 2013

Try it like this:

$stmt = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
    $stmt->bindValue(":username", $username, PDO::PARAM_STR);
    $stmt->bindValue(":password", $password, PDO::PARAM_STR);
    $stmt->execute();

You have to create a statement ($stmt) via $db->prepare("sql") not a query. Then you can bind params to the prepared statement and execute it.