-1
<?php 
include 'dbconnect.php';
 ob_start();
 session_start();


 $username = "";
 $password = "";

 if(isset($_POST['submit'])){
    $username = $_POST['username'];
    $password = $_POST['password'];
    }


 $sql= 'SELECT * FROM login WHERE username=:username AND password=:password';

 $query = $link->prepare($sql);

 $query->execute(array(':username' => $username, ':password' => $password));


 if(mysqli_num_rows($query)== 0){
  header('Location: index.php?err=1');
 }else{

  $row = mysqli_fetch_assoc($query);

  session_regenerate_id();
  $_SESSION['sess_user_id'] = $row['id'];
  $_SESSION['sess_username'] = $row['username'];
  $_SESSION['sess_userrole'] = $row['role'];

  echo $_SESSION['sess_userrole'];
  session_write_close();

  if( $_SESSION['sess_userrole'] == "admin"){
   header('Location: admin.php');
  }else{
   header('Location: user.php');
  }

  }

?>

I am getting this error may i know where am i going wrong just to learn better "Call to a member function execute() on boolean" Help me with a better solution The database is connected and also form input username and password is correct also the below statement is correct need help with this query execute part

shyamm
  • 506
  • 6
  • 17
Jinam Shah
  • 31
  • 7

3 Answers3

0
$query = $link->prepare($sql);

is returning false instead of an object, when you try to run an object function on "false" it fails.

$query = $link->prepare($sql);
if ($query instanceof {whatever object type it has to be})
{
     $query->execute(array(':username' => $username, ':password' => $password));
     // rest of your code
}else{
     throw new \Exception("query builder failed");
}
Auris
  • 1,309
  • 1
  • 9
  • 18
0

From the docs:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

Since execute is tried to be called on a boolean, it means that prepare returned FALSE, so the statement was not successfully prepared. You need to check your query's correctness. Is your table and fields existent? If you run such a query with arbitrary values for username and password, will it be successfully executed? Wild guess: you might have a problem with password, which is a keyword as well, you might want to use password instead of password in your query.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

Try with this in dbconnect.php

    $link = new PDO('mysql:host=localhost;dbname=task', 'root', '');