简体   繁体   English

使用while循环或其他方法消除多余的代码

[英]eliminating excess code with while loop or other

I have a select drop down list of items on my website and I want the total of each category in the list to have a number beside it that shows the total number of items in that category. 我在网站上有一个选择项下拉列表,我希望列表中每个类别的总数旁边有一个数字,以显示该类别中项目的总数。 I want my directory list of items to update when the user selects a category from my drop down list. 当用户从下拉列表中选择类别时,我希望更新目录列表。

I am having trouble coding it. 我在编码时遇到麻烦。 I have a table with the SiteTypes and SiteTypeID's called sitetypes. 我有一个带有SiteTypes和SiteTypeID的表,称为sitetypes。 And another table called sites with all the urls in the database which is what I want to display to my users. 还有另一个表称为站点,站点中包含数据库中的所有URL,这是我要向用户显示的内容。 There are different categories of urls, my select menu should display each category of urls when selected. 网址有不同的类别,选择后我的选择菜单应显示网址的每个类别。 I am having trouble figuring out how to display 我在弄清楚如何显示时遇到麻烦

$sql = "SELECT COUNT(u.url) AS total, u.SiteTypeID, p.SiteType FROM sites AS u LEFT JOIN sitetypes AS p USING (SiteTypeID) WHERE SiteTypeID=3";
$sq2 = mysqli_query($dbc, $sql);

$sq3 = "SELECT COUNT(u.url) AS total, u.SiteTypeID, p.SiteType FROM sites AS u LEFT JOIN sitetypes AS p USING (SiteTypeID) WHERE SiteTypeID=4";
$sq4 = mysqli_query($dbc, $sq3);

$sq5 = "SELECT COUNT(u.url) as total, u.SiteTypeID, p.SiteType FROM sites AS u LEFT JOIN sitetypes AS p USING (SiteTypeID) WHERE SiteTypeID=5";
$sq6 = mysqli_query($dbc, $sq5);


echo $row['url'] $row['SiteType']; 
echo $row2['url'] $row2['SiteType'];
echo $row3['url'] $row3['SiteType'];

I want to display the total number of urls in the database per category. 我想显示数据库中每个类别的URL总数。 Any ideas would be appreciated. 任何想法,将不胜感激。 I tried using while loops but I can't get it to work. 我尝试使用while循环,但无法正常工作。

I am a bit confused about exactly what you are trying to get (could you post some sample data and sample output?). 我对要获取的确切内容有些困惑(可以发布一些示例数据和示例输出吗?)。 However why not merge the 3 queries together? 但是,为什么不将3个查询合并在一起呢?

<?php

$sql = "SELECT COUNT(u.url) AS total, u.SiteTypeID, p.SiteType 
        FROM sites AS u 
        LEFT JOIN sitetypes AS p USING (SiteTypeID) 
        WHERE SiteTypeID IN (3, 4, 5)
        GROUP BY u.SiteTypeID, p.SiteType";

if ($sql2 = mysqli_query($dbc, $sql))
{
    while ($row = mysqli_fetch_assoc($sql2)) 
    {
        echo $row["total"].." - ".$row["SiteTypeID"].." - ".$row["SiteType"]."<br >";
    }
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM