Allowable fatal error: object of class mysqli_result cannot be converted to string in php
I am taking data from a product table. I can't figure out what this error is.
Product
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="tianen"; // Database name
$tbl_name="product";
$con = mysqli_connect("127.0.0.1","root","","tianen");
$result=mysqli_query($con,"SELECT * FROM product");
echo"$result";
?>
source to share
Problem
You cannot echo $result
because it is not a string. It is an object . What it returns if your request works . mysqli_result
mysqli_query
You cannot echo
an object in PHP unless it has a magic method , Object has no such method , so it cannot be ed. So the error is. __toString
mysqli_result
echo
Decision
What you want to do is loop over the results using one of the methods or functionsfetch_*
for example mysqli_fetch_assoc()
. The documentation contains examples and there are many good tutorials on using MySQLi out there.
Here's an example using mysqli_fetch_assoc()
:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="tianen"; // Database name
$tbl_name="product";
$con = mysqli_connect("127.0.0.1","root","","tianen");
$result=mysqli_query($con,"SELECT * FROM product");
if ($result) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
// do things with $row, an associative array with keys matching your table column names
}
?>
source to share
mysqli_query will return an object from which you should retrieve rows. Once you have the rows, you can access the fields from each row.
The way I do it is to loop through the mysqli result (I'm not sure if there is another way):
// Create an empty array to store rows
$rows = [];
// The fetch_assoc function will automatically generate an iterator to return false when there are no more rows to fetch.
// Each result will be a row in the form of an associative array
while ($row = mysqli_fetch_assoc($con, $result)) {
array_push($rows, $row);
}
There is also another way to use mysqli as objects, which I find easier, since 1. the function names are shorter and 2. you don't need to keep passing in $ con parameters. instead you would say$result = $con->query("SELECT ...");
source to share