How to sum all data from a table

Asked

Viewed 75 times

-1

I have the 'orders' table where all the orders that were made are, I would just add all the orders and show on the screen.

inserir a descrição da imagem aqui

In the example above I have 8 orders, on the screen will simply have "Number of orders made 8", if you understood.

    <?php 
        require  'conexao_pedidos.php';
        $sql = query("SELECT order_id FROM orders GROUP BY order_id;");
        $result=$conn->query($sql);
        while($row=$result->fetch_assoc()){
    ?>
    <div class="text-center"><?=  $row ?></div>
    <?php
		}
		?>

  • You want to count how many records you have in a table?

  • exactly and show screen.

  • 1

    Enter the code you are using to query the table. In practice, just select everything in the table and count how many items came with the count.

  • I added in the question the code I have so far.

1 answer

2

To count the number of records from a table you have two options, or by SQL using the aggregate function COUNT(*) that returns the count of the number of rows recovered in a query or by PHP through property num_row of the object mysqli_result(I believe to be mysqli because PDO does not have the method fetch_assoc()).

By SQL using COUNT(*):

$sql = query("SELECT COUNT(*) as pedidos FROM orders;"); //Aqui eu não entendi o uso do GROUP BY order_id pois order_id parece ser a chave primária da tabela
$row= $conn->query($sql)->fetch_assoc(); // A consulta irá retornar apenas uma linha
echo "Número de pedidos: ".$row['pedidos'];

By PHP using mysqli_result::num_rows:

$sql = query("SELECT order_id FROM orders;");
$result= $conn->query($sql);
echo "Número de pedidos: ".$result->num_rows;
  • I am doing this and is not returning anything in either of the two options. <? php include 'header.php'; require'connection_requests'; $sql = query("SELECT order_id FROM Orders;"); $result= $Conn->query($sql); echo "Number of requests: ". $result->num_rows; ?>

  • What is being returned?

  • no data, it’s all blank

  • If you do this query SELECT * FROM orders what the result?

Browser other questions tagged

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