PDO: Call to a member function fetch() on a non-object? [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 years ago.
I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn't it already on the $this->db object?
class shoutbox {
private $db;
function __construct($dbname, $username, $password, $host = "localhost" )
{ # db conections
try {
$this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
function getShouts()
{
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0');
return $sql_shouts->fetch(PDO::FETCH_OBJ);
}
}

Look carefully at the documentation for PDO::query, particularly the "Return Values" section:
PDO::query() returns a PDOStatement
object, or FALSE on failure.
The important bit is "FALSE on failure". FALSE is not an object, so calling ->fetch() is bad news.
The error is probably due to your use of "==" comparison operator. In SQL, it's just "=".
You should test that the $sql_shouts is not false, and then do something smart with the error, if there was one:
<?PHP
$sql_shouts = $this->db->query('...');
if ($sql_shouts === false){
$errorInfo = $this->db->errorInfo();
//log the error or take some other smart action
}
return $sql_shouts->fetch(PDO::FETCH_OBJ);

I would say that your query is not executing due to incorrect syntax. You should really check PDO's errorinfo static function to see if the query errored out or not.
Here is a potential correct SQL statement:
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, `time` FROM shouts WHERE pmuserid = 0');
I believe Time is a reserved word in MySQL I would recommend using a different name but encasing it in backticks will alleviate that issue. 1 equal sign is used for mysql, not two. But yea, look into the errorinfo function to determine if your query failed due to a syntax error and handle it gracefully.

It happens when the table doesn't exist also. make sure it actually exists, and isn't just a holder in the database due to hard drive errors.
When that happens I suggest you recreate the database/table.

I got this error message due to a silly mistake with brackets. It was nested inside an if statement and just didn't see it.
db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var)->fetchField());
It took me a while to work out that I didn't close the db_query bracket in the right place. Maybe it helps someone else staring at this wondering wth. Correct:
db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var))->fetchField();

Related

Handle PHP objects on declaration file for every method call [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
MySQLi prepared statements error reporting [duplicate]
(3 answers)
Closed 4 years ago.
I am looking for a way to build a handler or edit a php object, the following is an example for mysqli
I have a system with many files using the mysqli object in a variable
$my_var=new mysqli($host, $user, $pass, $base);
Files call this to do queries and get the results like this:
$q=$my_var->query("SELECT * FROM table");
$q->fetch_assoc();
if there is an error on the query, $my_var->error will be populated on the first line and will throw an error 500 on the second line.
I am looking for a way to build a handler for $my_var->error and throw the error before any fetch_* method is called, so,
is there any way to build a handler/listener for $my_var->error?
if this is not possible, is there any way to override mysqli fetch_assoc(), fetch_row() and fetch_array() methods to check if $my_var->error is true and show the error before continue?
I know about try{}catch(), throw new Exception and or die() methods, but these mean to edit every fetch_* in the system, I would like to do it editing the connection file only.
Thank you!
---editing---
I think prepared statements are not what I am looking for.
---editing 2---
And no, I am not looking how to get mysqli errors.
Thank you for your help fyrye!
---Answer Final Code---
class mysqli2{
private $c;
function __construct(...$args){ // open connection
$this->c=new mysqli(...$args);
if(!empty($this->c->error)){ // check for errors
echo("<script>console.error(\"MySQL: ".$this->c->error."\");</script>");
}
}
function query($query, $resultmode = MYSQLI_STORE_RESULT){
$r=$this->c->query($query, $resultmode); // make query
if(!empty($this->c->error)){ // check for errors
echo("<script>console.error(\"MySQL: ".$this->c->error."\");</script>");
}
return $r; // returns query results
}
function __call($method, $args){ // calls others mysqli methods
return $this->c->$method(...$args);
}
function __get($name){ // get all the properties
return $this->c->$name;
}
function __set($name, $value){ // set all the properties
if (property_exists($this->c, $name))$this->c->$name = $value;
}
}
To suggest a best practice, when using either PDO or MySQLi extensions, it is suggested to always check the return results from any of the usable methods, before moving on to a method that relies on its result.
As mysqli::query returns false on an error, it should be checked before using fetch_assoc, instead of assuming it is not false. The same applies to using fetch_assoc, as it can return NULL;
if (!$q = $my_var->query($sql)) {
//something went wrong - handle the error here.
}
if ($data = $q->fetch_assoc()) {
echo $data['column'];
}
However as I suggested, you would need to create an abstraction layer.
Since $q would be false on error, the exception from the code in your question would be:
Fatal error: Call to a member function fetch_assoc() on boolean
Meaning you would not be able to override the fetch_* methods, without overriding mysqli::query to always return an object.
Please do not use in production code.
This is only an example of how to override the mysqli::query method with your own. You would also need to override all other mysqli::*** methods, like prepare, commit, etc.
Example https://3v4l.org/PlZEs
class Conn
{
private $conn;
public function __construct(...$args)
{
$this->conn = new mysqli(...$args);
}
public function query($query, $resultmode = \MYSQLI_STORE_RESULT)
{
$d = $this->conn->query($query, $resultmode);
if (!empty($this->conn->error)) {
throw new \RuntimeException($this->conn->error);
}
return $d;
}
}
//Your connection code
$con = 'my_var';
$$con = new Conn('host', 'user', 'pass', 'base');
//example usage of valid query
$q = $my_var->query('Valid Query');
$q->fetch_assoc();
//example use of invalid query throwing an exception before `fetch_assoc`
$q = $my_var->query('This is not valid');
$q->fetch_assoc();
Results
I was successful
-----
Fatal error: Uncaught exception 'RuntimeException' with message 'Expected "Valid Query"' in /in/PlZEs:51
Stack trace:
#0 /in/PlZEs(70): Conn->query('This is not val...')
#1 {main}
thrown in /in/PlZEs on line 51
This approach uses PHP 5.6 argument packing and unpacking, to match the function call arguments, to prevent having to manually define them.
It is possible to expand on this to write a message to log file, send an email, trigger an event, or display a friendly error message instead of throwing an exception. As well as overriding the mysqli_stmt responses with your own Statement object(s).

PHP mysql fatal error Call to a member function fetch_assoc() [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

Call to a member function [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

Call to a member function fetch_assoc() [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

Fatal error: Call to a member function fetch_assoc() on a non-object [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

Categories