save the value of a query in a php variable

1

I want to save the value of a select to a php variable, and then display it in the html.

I tried something like:

function totalEspumas(){
    $banco = abrirBanco();
    $quantidade_pedidos = "SELECT SUM(quantidade) from pedidos";
    $resultado = $banco->query($quantidade_pedidos);
    $banco->close();
    $pedidos = '';

    while($row = mysqli_fetch_array($resultado)){
        $pedidos[] = $row;
    }

    return $pedidos;
}

The result of the query is 23. Html:

<?php
$totalespuma = totalEspumas();
?>
<?php  echo $totalespuma ?>

When I try to show the value of the variable, I get:

Catchable fatal error: Object of class mysqli_result could not be converted to string
    
asked by anonymous 04.04.2018 / 15:24

3 answers

0

You are storing mysqli_result in the array. The correct code looks like this:

function totalEspumas(){
    $banco = abrirBanco();
    $quantidade_pedidos = "SELECT SUM(quantidade) as total from pedidos";
    $resultado = $banco->query($quantidade_pedidos);
    $banco->close();
    $pedidos = '';

    while($row = mysqli_fetch_array($resultado)){
       $pedidos[] = $row['total'];
    }

    return $pedidos;
}
    
04.04.2018 / 15:29
0

If you are trying to give one:

echo totalEspumas();

It's wrong, since it returns an array, the right one would be:

$var = totalEspumas();

echo $var[seu_index];

If you want to see everything in the array, make a

var_dump($var);
    
04.04.2018 / 15:28
0

Try as an example:

$connection = conectadb();
$sql = "SELECT SUM(quantidade) from pedidos";

$result = $connection->query($sql);
$row = $result->fetch_assoc();
$sum = $row->value_sum;

And the return gets $ sum .... will have to test there.

    
04.04.2018 / 15:37