如何从数据库中按类别显示数据? [英] How to display data in categories from database?
问题描述
所以我的网站允许用户创建联系人列表,现在我添加了用户命名的类别.我目前正在使用从我的 SQL 查询生成的关联数组的 while 循环显示联系人列表.
So my website allows users to create a contacts list and now I have added user-named categories. I am currently displaying the list of contacts using a while loop of the associative array generated from my SQL query.
所以它看起来像这样:
Contacts:
Contact 1
Contact 2
Contact 3
现在我在数据库中有一个用于联系人类别的新列,但我无法弄清楚如何对它们进行排序,以及如何显示联系人类别的名称.我试图让它看起来像这样:
Now I have a new column in the database for categories of contacts, and I cannot figure out how to order them by, and display the name of the contact category. I am trying to get it to look like this:
Contacts:
Category 1
Contact 1
Contact 2
Contact 3
Category 2
Contact 1
Contact 2
Contact 3
如果你需要我的实际代码:
My actual code if you need it:
<?php
//START CONTACTS LOOP
$contacts_query = "SELECT id, name FROM contacts WHERE ownerid = '$userID' ORDER BY `name` ASC";
$run_contacts_query = mysql_query($contacts_query);
if($run_contacts_query){
while($c_data = mysql_fetch_assoc($run_contacts_query)){
$id = $c_data['id'];
$name = $c_data['name'];
?>
<li><a href="contact.php?id=<?=$id?>"><?=$name?></a></li>
<?php
}} //END CONTACTS LOOP
?>
推荐答案
也只是检索类别并先按类别然后按名称排序.并检查类别是否与上一个不同:
Just also retrieve the category and sort first by category and then by name. And check whether the category is different than the last:
$contacts_query = "SELECT id, name, category";
$contacts_query.= " FROM contacts";
$contacts_query.= " WHERE ownerid = '$userID'";
$contacts_query.= " ORDER BY `category`, `name` ASC";
$run_contacts_query = mysql_query($contacts_query);
if($run_contacts_query) {
$currentCategory = null;
while($c_data = mysql_fetch_assoc($run_contacts_query)){
if ($c_data['category'] != $currentCategory) {
echo '<li>' . $c_data['category'] . '</li>';
$currentCategory = $c_data['category'];
}
echo '<li><a href="contact.php?id=' . $id . '">' . $name . '</a></li>';
}
}
这篇关于如何从数据库中按类别显示数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!