【发布时间】:2014-06-14 23:00:09
【问题描述】:
我的表包含 10 个日期时间列 (item1 - item10),代表我的成员提供的 10 项服务。在任何给定的“市/县”中,10 种服务中的每一种都只有 12 个职位。基本上,我需要将每列中最旧的十二个日期时间分别返回为“item1”、“item2”、“item3”等,否则返回为“”。
item#'s 回显到成员的列表中,我使用 jquery 过滤列表。
我当前的代码设置了一个限制,但不是根据日期时间。如果页面上的所有位置都已填满,则会出现问题。如果高级成员决定提供额外服务,他们可以“淘汰”新成员。
如果我没有很好地解释这一点,这里有一个工作示例: http://integritycontractingofva.com/pest_control/Richmond_VA.php
$result = @mysqli_query($db, "SELECT * FROM table WHERE category LIKE '%$category%' AND territories LIKE '%$area.%' AND exp >= NOW()");
if (!$result){echo ("<p>Error performing listing query:" . mysql_error() . "</p>");}
$item1cnt = $item2cnt = $item3cnt = $item4cnt = $item5cnt = $item6cnt = $item7cnt = $item8cnt = $item9cnt = $item10cnt = 0; //start counter at "0"
$items = array();
$today = date('Y-m-d');
while ($row = mysqli_fetch_array($result)){
if($row["exp"] > $today){
if($row["item1"]!="0000-00-00 00:00:00"){ // if datetime is set
$item1cnt++; // add one to counter
if($item1cnt > 12){ // if counter is greater than 12
$row["item1"]=""; // itemx = ""
}else{ // if counter is less than 12
$row["item1"]="item1"; // item = itemx
}
}else{ // if datetime is not set
$row["item1"]=""; // itemx = ""
}
// repeat above for all 10 items
// part of member's listing used by jquery to filter services
$items[] = "<li class=\"services " . $row["item1"] . " " . $row["item2"] . " " . $row["item3"] . " " . $row["item4"] . " " . $row["item5"] . " " . $row["item6"] . " " . $row["item7"] . " " . $row["item8"] . " " . $row["item9"] . " " . $row["item10"] . "\">";
}
}
如果成员为item1、item3 和item9 设置了日期时间,则打印结果将为<li class="services item1 item3 item9">
【问题讨论】:
-
天哪,您介意更好地格式化您的代码以使其更具可读性吗?
-
我想这应该在纯 MySQL 中以某种方式完成,而不是遍历表的所有记录。为了让您了解更改 SQL 以选择最后 10 个(项目)* 12(实体)= 最多 120 条记录,就像这样
SELECT * FROM table WHERE ... ORDER BY item1 desc, item2 desc, ..., item10 desc LIMIT 120;这样您至少可以将您的提取减少到最多 120 条记录。 -
为了清楚起见,我已经编辑了代码。我喜欢你添加 LIMIT 的想法。
-
并在 SQL 中添加
WHERE exp>NOW()(我理解的只是未过期的许可证),而您不必在 PHP 中这样做。 PHP 应该只接收必要的数据记录。 -
所以你不需要这行
if($row["exp"] > $today)