Undefined fetchAll and fetch in returned PDOStatement

I am just starting out with PDO and looking in several tutorials for an answer, but I just can't get it to 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; 

I get that it can return the number of results But why? And why this gives me a fetch / fetchAll notification has not even been announced. I don't get an exception either.

+4
source share
1 answer

You need to use a method call with parameterization:

 $sth->fetchAll(); 

Or $ sth-> fetch ();

not so easy

 $sth->fetchAll; 

PHP thinks you're trying to get into a property called fetchAll!

+8
source

Source: https://habr.com/ru/post/1443058/


All Articles