store the value of a query in a php variable

Asked

Viewed 963 times

1

I want to save the value of a select to a php variable, and then show it in 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 variable value, I get:

Catchable fatal error: Object of class mysqli_result could not be converted to string
  • You must be trying to give an echo totalEspumas();, it returns an array, it cannot be done like this

3 answers

0

If you’re trying to give a:

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);

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;
}
  • It worked, but in html I had to use: <td align="center"> <?php echo $totalfoam[0] ? > </td> I don’t know if it’s the best practice but it worked

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 is $sum.... will have to test there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.