0

I generate a list from the data in my sql database. The problem is that the list prints the "System" name before each remark instead of listing the "Remark" for all rows containing the same "System" name under one .

Code:

<?php
require("dbcon.php");
$query = " 
    SELECT 
        id, 
        Date, 
        System,
        Remark
    FROM records
    WHERE Date BETWEEN '$from' AND '$to'
    ORDER BY Date
    ";
echo "<div id='heading'>EVENT LOG: Last week</div><br />";

$result = mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
    <ul><?php echo $row["System"]; ?>
    <li><?php echo $row["Remark"]; ?></li></ul>
<?php } ?>

This gives me a output like:

Systemname1
- Log entry for Systemname 1 (stored under Remark in database)
Systemname1
- Log entry for Systemname 1 
Systemname2
- Log entry for Systemname 2
Systemname2
- Log entry for Systemname 2

But what I want is:

Systemname1
- Log entry for Systemname 1
- Log entry for Systemname 1

Systemname2
- Log entry for Systemname 2
- Log entry for Systemname 2

This can probably be fixed in some way by using foreach(), but I'm not sure how :/

4

3 回答 3

0

我会选择使用临时变量来与日期进行比较,但是这个问题有多种解决方案:

$result = mysql_query($query);
$temp_date = '';
if(mysql_num_rows($result)) {
  echo "<ul>";  // Start the list only if data exist
  while ($row=mysql_fetch_array($result)) {
    if($row["Date"]!=$temp_date) {  // If 'Date' is equal to the previous one, skip
      if($temp_date!='') {  // If it's not the first list 
        echo "</ul><ul>";   // close the previous one and start another
      } 
      echo $row["Date"];
      $temp_date=$row["Date"]; 
    }
    echo "<li>".$row["Remark"]."</li>";
  }
  echo "</ul>";
}
于 2013-10-04T14:57:35.037 回答
0

您的查询是正确的:)

我会用代码分两步解决这个问题:

首先将 sql 结果格式化为可用于渲染的内容:

$nestedResult = array();
foreach (mysql_fetch_assoc($result) as $row) {
    if (!isset($nestedResult[$row['Date']])) {
        $nestedResult[$row['Date']] = array();
    }
    $nestedResult[$row['Date']][] = $row['Remark'];
}

然后是实际渲染:

echo '<ul>';
foreach ($nestedResult as $date => $remarks) {
    echo '<li>' . htmlspecialchars($date) . '<ul>';
    foreach ($remarks as $remark) {
        echo '<li>' . htmlspecialchars($remark) . '</li>';
    }
    echo '</ul></li>';
}
echo '</ul>';
于 2013-10-04T15:20:19.140 回答
0

您可以在 PHP 中进行所有排序和组合,但这里有一个选项,数据库进行分组:

<?php
require("dbcon.php");
$query = " 
    SELECT 
        id, 
        Date, 
        System,
        GROUP_CONCAT(Remark, SEPARATOR ':::') AS Remark
    FROM records
    WHERE Date BETWEEN '$from' AND '$to'
    ORDER BY Date
    GROUP BY Date
    ";
echo "<div id='heading'>EVENT LOG: Last week</div><br />";

$result = mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
    <ul><?php echo $row["Date"]; ?>
    <?php foreach(explode(':::', $row["Remark"]) as $remark) { ?>
        <li><?php echo $remark; ?></li>
    <?php } // END foreach ?>
    </ul>
<?php } // END while ?>
于 2013-10-04T14:37:03.537 回答