Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch() on a non-object

Tags:

php

pdo

mysqli

I keep getting the same error message...
Fatal error: Call to a member function fetch() on a non-object
I've tried:
- removing quotes from ':user' and ':pass'
- changing fetch() to fetchAll()
- using PDO::FETCH_ASSOC

I can't seem to find a question that solves this, they all are solid SQL statements, there's no variables inside them.

$q = $dbh->prepare("SELECT * FROM users WHERE username= ':user' AND password= ':pass' ");
    $q -> bindParam(':user', $username);
    $q -> bindParam(':pass', $password);
    $result = $q -> execute();
    $numrows = count($result);
    echo $numrows;
    if($numrows == 1){
        while($row = $result->fetch(PDO::FETCH_OBJ)){
            $row["id"] = $_SESSION["id"];
            $row["username"] = $_SESSION["username"];
            $row["password"] = $_SESSION["password"];
            $row["email"] = $_SESSION["email"];
        }
    } else {
        header("location: index.php?p=5");
    }
like image 695
David Yue Avatar asked May 03 '26 19:05

David Yue


2 Answers

Fetch should be used on the PDOstatement object.

According to the PDO manual:

PDOStatement::fetch — Fetches the next row from a result set

The fetch function is a member function of the PDOStatement object. Example from the manual:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute(); //no need in another variable, like: $r = $sth->

/* Exercise PDOStatement::fetch styles */
$result = $sth->fetch(PDO::FETCH_ASSOC); //$sth, not "$r"

Another note: Regarding your usage of execute, according to the manual it returns a boolean value (true/false) and not an array of values.

I believe you've used mySQL so the "migration" to PDO is a bit strange for you, look at the manual and follow some tutorials.

like image 105
Ofir Baruch Avatar answered May 05 '26 08:05

Ofir Baruch


Remove quote from user and pass

$q = $dbh->prepare(" SELECT * FROM users WHERE username= :user AND password= :pass");
like image 38
Saty Avatar answered May 05 '26 08:05

Saty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!