2013-05-13 72 views
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是第$row下方。但是像这样的东西是行不通的。(无限循环)。

$row = mysql_fetch_array($result); 

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

while($row) { 
// echoes here 
} 

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

回答

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. 
} 
?> 

现在每当类别名称发生更改时,标题都将打印在说明中。请记住,您的查询确实需要在category_name上有ORDER BY才能正常工作,否则您可能会得到重复的标头。

+0

我喜欢这个解决方案!快速简单,就是我想要的。我也会研究mysqli。我听说过它,但不知道mysql已被弃用。 – Linkjuice57 2013-05-13 11:27:34

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 
}