How can I get the total sum of a column in a mysql table?

0

I have a product table and I wanted to do the sum of the row price in php How should I write the code select?

Try to do it that way:

$consulta="Select SUM(precio) FROM productos";

It does not work. Help.

    
asked by Wid Maer 05.09.2017 в 15:41
source

3 answers

3

What I usually do when I have a function that produces a result of an operation (either sum, average, etc.) in a column, is to give it an alias, so that the name of the column that gives you the result of the query is called like this:

$consulta="SELECT SUM(precio) as TotalPrecios FROM productos";
$resultado=$con -> query($consulta);
$fila=$resultado->fetch_assoc(); //que te devuelve un array asociativo con el nombre del campo

$TotalPrecios=$fila['TotalPrecios']; //Este es el valor que acabas de calcular en la consulta

With the "as" what you do is not create a new row, you simply give a name to the column that returns your query. If you had any query and would like your "price" field to be called "unit price" to differentiate it from another field in the query you would do it with that sentence: ... price as unit price ...

This makes it easier for you to access the result of the query from the associative array that you create in the $ row variable.

    
answered by 05.09.2017 в 15:53
0

The "sum ()" function returns the sum of the values contained in the specified field. For example, we want to know how many books we have available for sale:

select sum(cantidad) from libros;
    
answered by 05.09.2017 в 19:12
0
prueba de la siguiente manera quizas funcione.

<?php


        require('conexion.php');

        $consultas="SELECT *  FROM alumnos";

        $resultados=$conectahugo->query($consultas);

        while($columnas=$resultados->fetch_assoc()){

        echo $columnas['id'],' ';
        echo $columnas['nombre'],' ';
        echo $columnas['apellidos'],' ';
        echo $columnas['edad'],' ';


        echo '<br>';
        }

? >

    
answered by 06.09.2017 в 20:38