Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

victor guia
victor guia
8,098 Points

echo query result in php

Hi,

I have the following mysql query in php:

<?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,948 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,730 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