I have an SQL which returns records in a mysql table. Each record has many fields, and one of the field called “type” which is the type of sample. All samples are broadly classified into six types. I am displaying all the records in the table. But I want to group the data by ‘type’ and show separate tables with type as side heading. At present I use this script.
echo ”
USIN | Type | Date of Coll. | Location | Description | H3 | Cs | Sr | Analyst |
---|
while($data=mysql_fetch_array($result)){
echo ”
“;
echo ”
“.$data[‘usin’].””;
echo ”
“.$data[‘type’].””;
echo ”
“.$data[‘doc1’].””;
echo ”
“.$data[‘location’].””;
echo ”
“.$data[‘description’].””;
echo ”
“.$data[‘h3’].””;
echo ”
“.$data[‘cs’].””;
echo ”
“.$data[‘sr’].””;
echo ”
“.$data[‘name’].””;
echo”
“;
}
echo ”
“;
This displays all the records in one table. I want to break the table when all the records with same value in type field is displayed and begin a new table for next type of samples. (like group header) Is there any easy way other than running separate SQLs?
解决方案
Make sure your SQL query is ORDER BY type and then in your while loop you could do this:
$lastType = ”;
echo ‘
while($data=mysql_fetch_array($result)) {
if($lastType != ” && $lastType != $data[‘type’]) {
echo ‘
‘;
echo ‘
}
echo ”
“;
echo ”
“.$data[‘usin’].””;
echo ”
“.$data[‘type’].””;
echo ”
“.$data[‘doc1’].””;
echo ”
“.$data[‘location’].””;
echo ”
“.$data[‘description’].””;
echo ”
“.$data[‘h3’].””;
echo ”
“.$data[‘cs’].””;
echo ”
“.$data[‘sr’].””;
echo ”
“.$data[‘name’].””;
echo”
“;
$lastType = $data[‘type’];
}
echo ‘
‘;
I’ve not tested it but it whenever the type changes it will insert a closing and opening table tag (you can obviously add whatever else you want in there).