Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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,936 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: http://codular.com/php-mysqli