I run the PHP query but it does not display sum result in Mysql

Asked

Viewed 396 times

0

I’m having trouble displaying the following sum.

require_once("config_acesso.php");

$consultar = "SELECT SUM('valor') FROM vendascalc WHERE valor"; 
$resulta = mysqli_query($mysqli,$consultar);

echo "Total a pagar: " . $resulta;

I get no results. But in phpMyAdmin the result flows smoothly.

  • There is no mistake?

  • 6

    $query = "SELECT SUM('value') FROM vendascalc WHERE value"; ...value what?

  • 2

    http://php.net/manual/en/mysqli-result.fetch-row.php

2 answers

3

First hit query, remove single quotes from column valor, define an alias for the calculated field so it is more readable to retrieve the values in php, if no nickname is specified, php will assume that 'name' is the expression used, in case sum(valor) or 0(zero) if used mysqli_fetch_array()

$consultar = "SELECT SUM('valor') FROM vendascalc WHERE valor"; 

Change to:

$consultar = "SELECT SUM(valor) as total FROM vendascalc WHERE valor"; 

After the mysqli_query() recover the value of the consultation with mysqli_fetch_assoc() and make a loop to get all rows returned by query.

$resulta = mysqli_query($mysqli, $consultar);

while($item = mysqli_fetch_assoc($resulta)){
   echo $item['total'] .'<br>';
}
  • 1

    WHERE valor returns the lines where valor is not NULL, 0 or ''; is valid and may be the intention.

  • @bfavaretto, hehe did not know this syntax, seems to be better than using where valor is not null or valor <> '' and I’ll change the answer, thanks for the explanation.

-1

Your query is wrong, you need to have a value after WHERE:

SELECT SUM('valor') FROM vendascalc WHERE valor = <algum numero>
  • 1

    Eventually, the [Swer] guide may hint at why someone voted negative.

  • Thanks @lost, it was on the fly your tip. Thanks.

Browser other questions tagged

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