Fetch () for an object without an object

I get the same error ...
Fatal error: Calling member function fetch () for non-object
I tried:
- removing quotes from ": user" and ": pass"
- changing fetch()

to fetchAll()


- using PDO :: FETCH_ASSOC

I cannot find a question that solves this, they are all solid SQL statements, there are 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");
    }

      

+3


source to share


2 answers


Fetch should be used for a PDOstatement object.

According to the PDO guide :

PDOStatement :: fetch - fetch the next row from the result set

The function fetch

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: As far as your use execute

is concerned, according to the manual, it returns a boolean (true / false), not an array of values.

I believe you were using mySQL, so "going" to PDO is a bit strange for you, take a look at the manual and follow some tutorials.

+3


source


Remove quote from user

andpass



$q = $dbh->prepare(" SELECT * FROM users WHERE username= :user AND password= :pass");

      

+1


source







All Articles