How to return the sum of values of a column with limit in MySQLi

0

When I run directly on the bank

select sum(peso) from (select peso from dados order by id asc limit 2) as subt

Returns the expected value.

When I execute in PHP with the $num=2 variable, there is no value return or error.

$consultar = ("select sum(peso) from (select peso from dados order by id asc limit $num) as subt");

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

while($item = mysqli_fetch_assoc($resulta)){
       echo $item['subt'];
}
  

What I want is the sum of the values of the first two rows of the column peso of the table

What am I missing?

The table

DirectBankInquiry

    
asked by anonymous 11.07.2017 / 06:00

1 answer

2

The AS has to go in sum and not in the "source" of from , see that by its own image the column name came as sum ( weight) instead of subt :

TheASusedafterFROMwouldbetonamethetablesandnotthecolumns,soifyouwanttonamethecolumn

  

Notethesub-selectalsoneedsastoavoidtheerror:

    

Everyderivedtablemusthaveitsownalias.

Thescriptseemedtohavesomeproblems,sinceitsaidthatitcausedtheerror:

  

PHPWarning:mysqli_fetch_assoc()expectsparameter1tobemysqli_result,booleangivenin...72>>while($item=mysqli_fetch_assoc($results)){

Repeatthiswaybyalwayspassing$link:

<?php$link=mysqli_connect("seu dominio", "seu usuario", "sua senha", "nome do seu banco");

/* Verifica a conexão */
if (mysqli_connect_errno()) {
    printf("Conexão falhou: %s\n", mysqli_connect_error());
    exit;
}

$num = 2;

$consultar = "SELECT SUM(peso) AS subt FROM (SELECT peso FROM dados ORDER BY id ASC LIMIT $num) AS tabelaSubt";

if ($resulta = mysqli_query($link, $consultar)) {

    /* Pega os resultados */
    if ($item = mysqli_fetch_assoc($resulta)) {
        echo $item["subt"];
    }

    /* limpa os resultados */
    mysqli_free_result($resulta);
} else {
    /* Mostra o erro caso a query falhar */
    echo mysqli_error($link);
}

/* fecha a conexão */
mysqli_close($link);
    
11.07.2017 / 06:50