简体   繁体   中英

Get count of elements in a specific column of a MySQL table for each row

I have a MySQL table that has an array column whereas each element is delimited by a ",". I am try to get a total count of all rows (145)

When I run the following code I am getting 145 for $index which is correct but $totalClasses is 0. So obviously I am missing something.

I would appreciate it if someone would point out the error in my ways!

Thanks,

Vic

echo "<br><b>Number Classes Entered:</b>";
$SQL="SELECT ExhibitorClasses FROM tblShowEntries WHERE ShowID = $ShowID AND ExhibitorClasses IS NOT NULL AND ExhibitorClasses !=' '";


$result = mysql_query($SQL);
$myClasses = array(); // make a new array

$index = 0;
while($row = mysql_fetch_assoc($result)) // loop to get the count
{
     $myClasses[$index] = $row;
     $userclasses = count($myClasses[$index]);
     $totalclasses = $totalclasses + $userClasses;
     $index++;
}

//  $userClasses = explode(",", $myClasses);
//  $totalclasses = count($myClasses);
echo $index . " " . $totalclasses 

IN

$SQL="SELECT ExhibitorClasses FROM tblShowEntries WHERE ShowID = $ShowID AND ExhibitorClasses IS NOT NULL AND ExhibitorClasses !=' '";

you not concatenate var $ShowID correct is:

$SQL="SELECT ExhibitorClasses FROM tblShowEntries WHERE ShowID = ".$ShowID." AND ExhibitorClasses IS NOT NULL AND ExhibitorClasses !=' '";

Thanks to all who responded - Here is my final code. There may be a better way to do this but it works so guess thats ok.

$SQL="SELECT ExhibitorClasses FROM tblShowEntries WHERE ShowID = ".$ShowID." AND ExhibitorClasses IS NOT NULL AND ExhibitorClasses !=' '";

$result = mysql_query($SQL);
$myClasses = array(); // make a new array to hold my classes
$totalClasses=0;
$index = 0;

$query = mysql_query($SQL);
$row = mysql_fetch_row($query);
while($row = mysql_fetch_row($query)) // loop
{
    $myClasses[$index] = $row[0];
    $classes = explode(",", $myClasses[$index]);
    $count = 0;
    foreach ($classes as $item) {
       $count++;
    }
    $totalClasses = $totalClasses + $count;
    $index++;
}
echo "<br><b>Number Classes Entered:</b> ".$totalClasses;   

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