Home > Backend Development > PHP Tutorial > Why Am I Getting the 'Object of class mysqli_result could not be converted to string' Error in PHP?

Why Am I Getting the 'Object of class mysqli_result could not be converted to string' Error in PHP?

Susan Sarandon
Release: 2024-12-23 12:33:59
Original
533 people have browsed it

Why Am I Getting the

Error: Object of Class mysqli_result Could Not Be Converted to String

The error message "Object of class mysqli_result could not be converted to string" indicates that a MySQL query result is being improperly handled as a string.

Origin of the Error

In the provided code snippet, the mysqli_query() method is correctly used to execute a SELECT query on the learn_users table. However, the issue arises when attempting to convert the resulting object resource directly to a string and use it in the echo statement.

Solution

The mysqli_query() method returns an object resource that represents the result set of the query. This object resource cannot be directly treated as a string. To access the individual records in the result set, you need to iterate over them using the fetch_assoc() method.

Here's a corrected version of the code:

$result = mysqli_query($con, "SELECT classtype FROM learn_users WHERE username='abcde'");

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']. "<br>";
}
Copy after login

This code loops through the result set and retrieves each row as an associative array. The value of the 'classtype' column from each row is then printed separated by line breaks.

The above is the detailed content of Why Am I Getting the 'Object of class mysqli_result could not be converted to string' Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template