victor guia
victor guia
8,098 Points

echo query result in php


I have the following mysql query in php:

$con=mysqli_connect("localhost","root","password", "my_db");
//Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();

$query = "SELECT Balance FROM my_table ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($con, $query);

echo $result;

The echo $result does not work and I get a catchable fatal error that mysqli_query cannot be converted into string.

How do I echo my query result?

Thank you.

2 Answers

Aaron Kaye
Aaron Kaye
10,887 Points

I believe that is because result is an object and it is expecting a string. Try looking into the fetch command. I believe it would go something like

while($row = mysql_fetch_assoc($result)){
      $stringTest = $row['balance'];
      echo $stringTest;

Something like that!

Andrew McCormick
Andrew McCormick
17,729 Points

Per the mysqli_query spec : Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

So since you are querying a SELECT statement, it will return an object. And since you cannot use echo on an object you are getting the error.
If you just want to see the raw data use print_var($result) instead. Here are some example of what you can do with a mysqli query: