Add all the fields of the same column of several MySQL records

0

I have a table with several records, and let's say that each one collects the visits it has (for example). How can I get the total of visits?

But not of all, but of those who fulfill a condition. That is, if I have:

| Cat       | Visitas |
-----------------------
| Juegos    | 12      |
| Juegos    | 7       |
| Programas | 23      |

How do I get the sum of visitas of all records whose entry is Juegos ?

At the moment, the only thing I have done is the mySQL connection:

$conn = mysqli_connect($servername1, $username1, $password1, $dbname1);
$reg = mysqli_query($conn,
    "SELECT * FROM posts WHERE cat='$cat'")
or die( "Error al conectar con la base de datos 2: " . mysqli_error($conn) );

Thank you very much.

    
asked by ByBrayanYT - Tops y más 28.10.2018 в 13:03
source

1 answer

0

The first thing would be to create the connection and then you would have to make the query using SUM() of PHP to get the sum back. Then it would be something like that.

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "database");

/* comprobar la conexión */
if ($mysqli->connect_errno) {
    printf("Falló la conexión: %s\n", $mysqli->connect_error);
    exit();
}

$resultado = $mysqli->query('SELECT SUM(Visitas) FROM tabla WHERE Categoría = "jugador"');
$result = $result->fetch_assoc();
echo $result;

?>

And this would be everything.

    
answered by 28.10.2018 в 13:12