Error Object of class mysqli_result could not be converted to string when trying to display a value of a query in a php table

1

I am developing an inventory system where I have to show in a table the products with their respective stock and at the end the total stock of the whole warehouse.

I have the following code to show that total

$suma = mysqli_query($mysqli, "SELECT sum(stock) FROM  principal")
  or die('Error '.mysqli_error($mysqli));

<td width='80' height='13' align='center' valign='middle'>Total</td>
                                                            <td width='80' height='13' align='center' valign='middle'></td>
<td width='80' height='13' align='center' valign='middle'></td>
<td width='80' height='13' align='center' valign='middle'><?php echo $suma; ?></td>

But when loading the page I get the error

  

"Object of class mysqli_result could not be converted to string"

I understand that it is because the variable sum is not String , I think it is of type result but how could I convert it to show the total?

    
asked by Ivan Corona 16.02.2018 в 21:26
source

1 answer

2

The error is clear, mysqli_query returns mysqli_result that it is not possible to print as if it were a string, it is necessary to recover the value returned by the query. this is possible with fetch_assoc () as follows.

if ($resultado =mysqli_query($mysqli, "SELECT sum(stock) as suma FROM  principal")) {
    $row= mysqli_fetch_assoc($resultado);

    echo $row['suma'];
}
    
answered by 16.02.2018 / 21:42
source