如何修改SQL结果集,使结果为(A)而不是(B)。我需要以某种方式为每2个结果打破循环,以便将这两个结果包裹在行类中。请参阅以下内容:
(A)我喜欢发生什么:
<div class="row">
<div class="large-6 columns"></div>
<div class="large-6 columns"></div>
</div>
<div class="row">
<div class="large-6 columns"></div>
<div class="large-6 columns"></div>
</div>
(B)会发生什么:
<div class="row">
<div class="large-6 columns"></div>
<div class="large-6 columns"></div>
<div class="large-6 columns"></div>
<div class="large-6 columns"></div>
</div>
CODE:
<div class="row">
<?php $query = "SELECT * FROM recipe";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
?>
<div class="large-6 columns">
<h4><?php echo $row['recipe_title'] ?></h4>
<p><?php echo $row['recipe_description'] ?></p>
</div>
<?php } ?>
</div>
答案 0 :(得分:2)
您可以尝试添加一个计数器变量,每次调用循环时都会增加该变量。然后使用modulus operator关闭当前行并在调用循环两次后打开一个新行:
<div class="row">
<?php $query = "SELECT * FROM recipe";
$result = mysql_query($query);
$i = 1;
while($row = mysql_fetch_array($result)) {
?>
<div class="large-6 columns">
<h4><?php echo $row['recipe_title'] ?></h4>
<p><?php echo $row['recipe_description'] ?></p>
</div>
<?php
if($i % 2 === 0) {
echo '</div><div class="row">';
}
$i++;
}
?>
</div>
答案 1 :(得分:0)
最快/最脏:
while($row1 = mysql_fetch_assoc(...)) {
$row2 = mysql_fetch_assoc(...);
... output $row1 data
... output $row2 data
}
如果您只在结果集中获得偶数行,这将正常工作。否则,内部提取将在最后一行失败,因为while()提取消耗了最后一个结果。
答案 2 :(得分:0)
<?php
$query = "SELECT * FROM recipe";
$result = mysql_query($query);
$i = 0
while($row = mysql_fetch_array($result)) {
if ($i % 2 === 0) {
echo '<div class="row">';
}
?>
<div class="large-6 columns">
<h4><?php echo $row['recipe_title'] ?></h4>
<p><?php echo $row['recipe_description'] ?></p>
</div>
<?php
if ($i % 2 === 0) {
echo '</div>';
}
$i += 1;
?>
<?php } ?>
</div>