0

所以,通常我会遍历这样的数据库;

while($row = mysql_fetch_array($result)) {
 // echoes here
}

这很好用。但是,如果我想做一些事情怎么办?

<h1><?= $row["category_name"]; ?></h1>
<p><?= $row["description"]; </p>

while($row = mysql_fetch_array($result)) {
 // echoes here
}

这当然行不通,因为mysql_fetch_array低于 first $row。但是这样的事情不起作用..(无限循环)。

$row = mysql_fetch_array($result);

<h1><?= $row["category_name"]; ?></h1>
<p><?= $row["description"]; </p>

while($row) {
 // echoes here
}

解决这个问题的最佳方法是什么?第一个回声的另一个数据库查询?

4

2 回答 2

3

首先:停止使用mysql,它已被弃用。开始看mysqlipdo

现在我猜你所有的行都包含相同的数据category_name,这就是你想先打印它的原因。最简单的方法是跟踪您是否处于 while 循环的第一次迭代中。

<?php
$counter = 0;
while ($row = mysql_fetch_array($result)) {
   $counter++;
   if ($counter==1) {
    echo '<h1>'.$row['category_name'].'</h1><p>'.$row['description'].'</p>';

     //now if your first row only contains this information and doesnt have any regular data, uncomment the continue line.
     //continue;
   } 

   //echoes the regular rows.

}
?>

这也可以扩展以检查类别名称是否实际更改。因此,您可以在标题更改时打印标题。

<?php
$header = "";
while ($row = mysql_fetch_array($result)) {
   if ($header!=$row['category_name']) {
    echo '<h1>'.$row['category_name'].'</h1><p>'.$row['description'].'</p>';
    $header = $row['category_name'];
   } 

   //echoes the regular rows.
}
?>

现在每次类别名称更改时,标题都会打印描述。请记住,您的查询确实需要一个ORDER BYon category_name 才能正常工作,否则您最终可能会得到重复的标题。

于 2013-05-13T11:10:35.627 回答
2

仅获取第一行,将指针移动到第二行,然后循环遍历结果。

$row = mysql_fetch_array($result);

<h1><?= $row["category_name"]; ?></h1>
<p><?= $row["description"]; </p>

mysql_data_seek($result,1);

while($row= mysql_fetch_array($result)) {
   // echoes here
}
于 2013-05-13T11:10:25.933 回答