“在非对象上调用成员函数fetch_row()”尽管有错误处理[关闭]

“在非对象上调用成员函数fetch_row()”尽管有错误处理[关闭]

问题描述:

I want to execute a query but php/mysql throws

Call to a member function fetch_row() on a non-object

even though

if(!$results) 

should filter out empty results. The error message points to

$row = $results->fetch_row();

This is the whole code:

<?php
$query = 'DELETE FROM `products` WHERE `company` ='.$id_nummer;

$results = $link->query($query);
if(!$results)
{
  echo $link->error;
}
else
{
  $row = $results->fetch_row();
  $wanted_result = $row[0];
}
?>

Where is the cause for this?

EDIT: I solved it by replacing

if(!$results)

with

if(!is_object($results))

and it works.

You are trying to fetch a row from a a query as an object, however the query that you are making is a DELETE which doesn't return values that can be fetch as a row, but a boolean (TRUE or FALSE) that is the result of the query being successful or not. In this case, $result should return the value TRUE or FALSE, that can be used like this for example:

<?php
$query = 'DELETE FROM `products` WHERE `company` ='.$id_nummer;    
$results = $link->query($query);

if(!$results) {
    echo $link->error;
} else {
    echo "Company id:".$in_number." successfully deleted."
}
?>

You cannot fetch results from a DELETE query, as there are no rows to fetch. The contents of $results is a boolean true or false, based on success or failure of the DELETE.

In your case, it is TRUE, and your if (!$results) evaluates to FALSE, sending you into the else.

$results itself will tell you whether or not the action succeeded (whether the query was syntactically valid), but $link->affected_rows will tell you if you actually managed to match and delete any rows.

if ($result && $link->affected_rows > 0) {
  // You managed to delete something
}
else if ($result) {
  // successful query, no rows deleted
}
else {
  // Error
  echo $link->error;
}

Since you appear to be using MySQLi, consider creating a prepared statement instead of query() for this.

$stmt = $link->prepare("DELETE FROM `products` WHERE `company` = ?");
$stmt->bind_param('i', $id_nummer);
$stmt->execute();

// Then check affected rows
if ($stmt->affected_rows > 0) {
  // Successful deletion of some rows...
}