Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined fetchAll and fetch in an returned PDOStatement

I'm just beginning with PDO and have look up in several tutorials for an answer but I just can't make it work.

I got

Notice: Undefined property: PDOStatement::$fetch in E:\-------- on line 22 
Result: 1

with

$dsn = "mysql:host=localhost;dbname=the_database;";
try {
    $dbh = new PDO($dsn, "root", "");
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e){
    die( "failed conexion: ".$e->getMessage() );
}


$query = "SELECT MAX(price) AS max, MIN(price) AS min FROM cellphones";
try {
    $sth = $dbh->prepare($query);
    $sth->execute();
    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $result = $sth->fetchAll;
    }
catch(PDOException $e){
    echo $e->getMessage();
    }
die( "<br />Result: ".print_r($result, true) );

I get the same result with

$sth = $dbh->query($query);
$result = $sth->fetchAll;

and

$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetch;

What I do get is that it might be returning the count of results But why? And why it gives me a Notice about fetch / fetchAll not even declared. I don't get any exception either.

like image 735
Sdlion Avatar asked Feb 19 '23 15:02

Sdlion


1 Answers

You need to use the method call with paranthesis:

$sth->fetchAll();

Or $sth->fetch();

not just

$sth->fetchAll;

PHP thinks your trying to hit a property called fetchAll!

like image 85
Ray Avatar answered Feb 27 '23 11:02

Ray