简体   繁体   中英

Output distinct values in SQL column with PHP

I have a table with two collumns (shortened), NAME and CATEGORY.

I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.

I use this one:

$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");

This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.

Any help?

I want to output it in a table format.

EDIT: Here is my full code: (tablename is changed, and $con is removed)

$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");

while($row = mysql_fetch_array($test)) {
    echo $row['lkategori'] . ":" . $row['count'];
    die("test");
}       
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");

echo "<table border='1'>";
    while($row = mysqli_fetch_array($test)) {
        echo "<tr>";
        echo "<td>" . $row['lkategori'] . "</td>";
        echo "<td>" . $row['count'] . "</td>";
        echo "</tr>";
    }
echo "</table>";

This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.

EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:

$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");

use this

while($row = mysqli_fetch_array($test)) {
    echo $row['lkategori'] . ":" . $row['count'];
    die("test");
} 
Thanks 

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