Register Login

Object of Class mysqli_result Could Not be Converted to String Error

Updated Aug 02, 2020

It is common for programmers to encounter an error “Object of class mysqli_result could not be converted to string”. This error occurs when we want to print the value to an object as a string.

Let us look into this error in further detail.

What is Object of class mysqli_result Could Not be Converted to String Error?

The mysqli_query() function returns object resource to the result variable. It does not return a string. So, this result cannot be converted into a string and hence the error occurs.

To print the value of the object resource, we need to use mysql_fetch_array() or mysqli_fetch_assoc() functions to convert the value of the object to a string.

Error Code

<?php
$resultAll = mysqli_query($dbcon, "SELECT * FROM users");
if(!$resultAll){
	die(mysqli_error($dbcon));
}
echo $resultAll;
?>

Output:

Fatal error: Uncaught Error: Object of class mysqli_result could not be converted to string

Correct Example

<?php
$resultAll = mysqli_query($dbcon, "SELECT * FROM users");
if(!$resultAll){
	die(mysqli_error($dbcon));
}

if (mysqli_num_rows($resultAll) > 0) {
	while($rowData = mysqli_fetch_array($resultAll)){
  		echo $rowData["user_name"].'<br>';
	}
}
?>

In the above example, you can see that we are using mysqli_fetch_array() function to take the value from $resultAll object to $rowCatData array. Then the value of array element is printed using $rowCatData["user_name"];

Example 2 - Using mysqli_fetch_assoc()

The mysqli_fetch_assoc() method obtains a resultant row in the form of an associative array. The parameter is the result set identifier that is returned by mysqli_query() method.

<?php

$resultAll = mysqli_query($dbcon, "SELECT * FROM post_categorys");

# Die if connection net established
if(!$resultAll){
	die(mysqli_error($dbcon));
}

# Check if result greater then 0
if (mysqli_num_rows($resultAll) > 0){
	while($rowData = mysqli_fetch_assoc($resultAll)){
		echo $rowData["category_name"].'<br>';
	}
}

?>

In the above example, you can see that we are using mysqli_fetch_assoc() function to take the associative array from $resultAll object to assign it $rowCatData array. The value of array element $rowData["user_name"] is then printed.

Using fetch_array as an Object

<?php
while ($rowData= $resultAll->fetch_array()) {
    echo $rowData['classtype'];
}
?>

Here, the fetch_array() method is used for fetching the resultant row of the array as an object. The result assigned in $rowData['classtype'] is printed using the echo statement.

Using fetch_assoc as an Object 

<?php
while ($rowData= $resultAll->fetch_assoc()) {
    echo $rowData['classtype'];
}
?>

Here, the fetch_assoc() method is used for fetching the resultant row of the array as an object. The result assigned in $rowData['classtype'] is printed using the echo statement.


×