Call to undefined method mysqli_result::fetch()

I am able to fetch data from get_result() using any of fetch_assoc(), fetch_all(), …, and fetch_row() but when I am trying to use the simple fetch() only, I am getting this error

Uncaught Error: Call to undefined method mysqli_result::fetch()

Is this because of using get_result()? or am I missing something else in the following code

$stmt = $conn->prepare($SQL);
$stmt->bind_param("s", $date);
$stmt->execute();
$result = $stmt->get_result();
//$row = $result->fetch_assoc();
//$row = $result->fetch_all();
//$row = $result->fetch_row();
$row = $result->fetch();

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The variable $stmt is an object of the mysqli_stmt class. This class has a method called fetch() which returns a boolean (true/false). It is used only in conjunction with bind_result()

$stmt = $conn->prepare('SELECT myCol, myOtherCol FROM myTable WHERE dt=?');
$stmt->bind_param("s", $date);
$stmt->execute();
// The columns in SQL will be bound to the PHP variables
$stmt->bind_result($variable1, $variable2);
while ($stmt->fetch()) {
    // This will fetch each record from the prepared statement one by one
    printf ("myCol is %s and myOtherCol is %s\n", $variable1, $variable1);
}

$stmt->get_result() returns an object of class mysqli_result (which by the way is traversable using foreach). This class has different methods, but it doesn’t have fetch() method.

  • fetch_all() return an array of arrays. As the name suggests it returns all records from the result set at once.
    $result = $stmt->get_result();
    $allRecords = $result->fetch_all(\MYSQLI_ASSOC);
    echo json_encode($allRecords);
    
  • fetch_array() returns each record one by one as an 1D array
    $row = $result->fetch_array();
    printf("%s (%s)\n", $row["myCol"], $row["myOtherCol"]);
    
  • fetch_assoc() is the equivalent to fetch_array(\MYSQLI_ASSOC)
  • fetch_row() is the equivalent to fetch_array(\MYSQLI_NUM)
  • fetch_object() returns each record one by one as an object.
    $row = $result->fetch_object();
    printf("%s (%s)\n", $row->myCol, $row->myOtherCol);
    

However, to keep it simple you can just loop on the mysqli_result directly which will get you each row as an associative array.

foreach($stmt->get_result() as $row) {
    printf("%s (%s)\n", $row["myCol"], $row["myOtherCol"]);
}

Solution 2

There is no fetch() method on the mysqli_result object. It’s not clear what you’re expecting fetch() to return, but you’re probably looking at the fetch() method of the mysqli_stmt object.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply