Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

```

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 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top