How to return the sum of values of a limit column in Mysqli

Asked

Viewed 384 times

0

When I run directly in the bank

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

me returns the expected value.

When I run in PHP with the variable $num=2 no return value 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 lines of the column peso table

That I’m making a mistake?

The table

tabela

Direct consultation at the bank

sum

  • 1

    The problem seems to lie elsewhere, apart from the security flaw: http://ideone.com/7nkJnl

  • What I want is the sum of the values of the first two columns of the table

  • @Marceloboni nothing, neither sum nor error

  • Not accepting with the limit.

  • @Marceloboni >> connect Success

  • 2

    You set subt as the alias of your subquery I think the error is this " select sum(weight) total " you should access it like this : "echo $item['total']";

Show 1 more comment

1 answer

1


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

resultado

The AS used after the FROM would be to name the tables and not the columns, so if you want to name the column

Note the sub-select also needs to as to avoid error:

Every derived table must have its Own alias.

The script seemed to have some problems, since it said it caused the error:

PHP Warning: mysqli_fetch_assoc() expects Parameter 1 to be mysqli_result, Boolean Given in ... 72 >> while($item = mysqli_fetch_assoc($resulta)){

Remake like this by always passing the $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);
  • I answered that above tb in the comment divides the score huahauhauha

  • 1

    You are the guy !!!!!!!!!!!!!!!!!!!!

Browser other questions tagged

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