简体   繁体   中英

Count occurrences of value in row

I have a row in my mySQL database called "status" . In that row i got three different values, either "S", "R" or "L" .

Whats the easiest way to count and output the number of occurrences of each value with php?

Thanks!

It's hard to tell without a full look at your database, but the basic structure is this (assuming you have another row called id)

Edit: to demonstrate in php

$dbc = new mysqli($host, $username, $password, $dbname);    
$query = $dbc->query("select id, count(status) as status_count
    where status = 'S'
    group by id");
$query->fetch_assoc();
$row = $query->fetch_assoc();
echo $row['status_count'];

OR if you have more than one row do it like this:

while ($row = $query->fetch_assoc()) {

     echo $row['status_count'];


}

You can get the counts as separate rows with:

SELECT status, COUNT(*) as count
FROM yourTable
GROUP BY status

You can get them in a single row with:

SELECT SUM(status = 'S') AS s, SUM(status = 'L') AS l, SUM(status = 'R') as r
FROM yourTable

After this, you can read a single row of results:

$row = $pdo->fetch(PDO::FETCH_ASSOC);
$s_count = $row['s'];
$l_count = $row['l'];
$r_count = $row['r'];

The better way its to use a mysql query using COUNT

You can count all the raws SELECT COUNT(*) FROM DATABASE or one raw SELECT COUNT(colum_name) FROM DATABASE

To be more easy you can give it a variable name like this: SELECT COUNT (Colum_name) as name FROM DATABASE

So an example,after you connect to your database Use this:

$ query = mysql_query ('SELECT COUNT (R) as R   FROM status');

$ result = mysql_fetch_array ($ query);

Echo $ result ['R']

Hope this will help you !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM