4

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?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
user2936176
  • 51
  • 1
  • 1
  • 3

4 Answers4

3

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.

Hecke29
  • 766
  • 6
  • 18
0

You have to use prepare() not query()

Your code also is too bloated.

$stmt = $db->prepare("SELECT * FROM login where username=? AND password=?");
$stmt->execute([$_POST['username'], $_POST['password']]);

is enough
Also, you have to add this line after connect

$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

PDO::query return Values are PDOStatement object or FALSE on failure.

In your case a failure occurred and the returned value is FALSE instead of being a PDOStatement object.

Use var_dump right after $query = $db->query(... to make sure you are receiving an error. And use PDO error checking to find out what the error message is.

Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51
0

try use prepare() method instead of query()

$query = $db->prepare("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();
Vel
  • 9,027
  • 6
  • 34
  • 66
rray
  • 2,518
  • 1
  • 28
  • 38