Hi i m try to list categories separated by first letter, but i m confuse how to style using ul and li there is my query
$Sql = "SELECT *, COUNT(Cup_Id) AS num
FROM tabcup
INNER JOIN tabcats ON tabcupom.Cat_Id = tabcats.Cat_Id
WHERE tabcup.Cup_Status = 1
GROUP BY tabcup.Cat_Id
ORDER BY tabcat.Cat_Nome
";
$Query= mysql_query($Sql, $Conn) or die (mysql_error($Conn));
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
$Cats .= "<h2>$initial</h2>
";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>
";
}
echo $Cats;
this returns
<h2> A </h2>
<li> Aaaaaa</li>
<li> Abbbb</li>
<h2> B </h2>
<li> Baaaaa</li>
<li> Bbbbb</li>
the result im try is
<h2> A </h2>
<ul>
<li> Aaaaaa</li>
<li> Abbbb</li>
</ul>
<h2> B </h2>
<ul>
<li> Baaaaa</li>
<li> Bbbbb</li>
</ul>
Thanks for any help
Add a counter ($i
in my example) to your loop, so you know when to add the opening and closing tags,
$i = 0;
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
if ($i != 0) {
$Cats .= "</ul>";
}
$Cats .= "<h2>$initial</h2>
";
$Cats .= "<ul>";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>
";
$i++;
}
if ($i > 0) {
$Cats .= "</ul>";
}
$initial = null;
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
if ($initial) {
$Cats .= "</ul>
";
}
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
$Cats .= "<h2>$initial</h2>
<ul>
";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>
";
}
if ($Cats) {
$Cats .= "</ul>
";
}
Try this code:
$ind=0;
$Sql = "SELECT *, COUNT(Cup_Id) AS num
FROM tabcup
INNER JOIN tabcats ON tabcupom.Cat_Id = tabcats.Cat_Id
WHERE tabcup.Cup_Status = 1
GROUP BY tabcup.Cat_Id
ORDER BY tabcat.Cat_Nome
";
$Query= mysql_query($Sql, $Conn) or die (mysql_error($Conn));
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
if ($ind>0) $Cats.="</ul>
";
$ind++;
$Cats .= "<h2>$initial</h2>
";
$Cats.="<ul>";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>
";
}
echo $Cats;
if ($ind>0) echo "</ul>";