简体   繁体   中英

Count unique values in table column - result is always 1

I am wondering if someone might be able to spot where I'm going wrong here? I want to return the number of unique values for a column. When I run this query on Phpmyadmin the result is correct, but when I try to do it through PHP I keep getting the result 1.

//Find out number of unique slotids and assign to variable
    $q2= "SELECT COUNT( DISTINCT(`slotid`) ) FROM `individualavailability`";
    $result2 = mysqli_query ($dbcon, $q2);
    $count = mysqli_num_rows ($result2);
    echo $count. " slot ids";

The mysqli_num_rows function returns the number of rows you read from the server, not the number of slotid counted by your query. Something like this should work better:

$q2= "SELECT COUNT( DISTINCT(`slotid`) ) as cnt FROM `individualavailability`";
$r2 = mysqli_query ($dbcon, $q2);
$row = mysqli_fetch_assoc($r2);
echo $row["cnt"];
$query=("SELECT count(DISTINCT (`slotid`)) as total from `individualavailability`");
$result=mysqli_query ($dbcon, $query);
$row=mysqli_fetch_assoc($result);
echo $row['total'];

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