如何在while循环中重启php

时间:2018-07-23 15:56:28

标签: php while-loop

我在mysql数据库表中有5行数据。我想随机显示这五行,所以我使用ORDER BY rand()函数,但是问题是我想在获取2行后停止while循环,并在其中添加一些html,然后从第3行继续。这可能吗?

这是我尝试的代码,但是此代码的问题是我得到2行重复90%的时间...

<?php

$query = "SELECT * FROM table ORDER BY rand() LIMIT 2";

$result = mysqli_query($connection,$query);

while($row = mysqli_fetch_assoc($result)){

//display till 2 rows

?>

<!-- add some html block -->

<?php

$query = "SELECT * FROM table ORDER BY rand()";

$result = mysqli_query($connection,$query);

mysqli_data_seek($result,2);

while($row = mysqli_fetch_assoc($result)){

//display from row 3 now till last row

?>

2 个答案:

答案 0 :(得分:4)

为什么不只使用一个查询和一个循环?

$query = "SELECT * FROM table ORDER BY rand()";
$result = mysqli_query($connection,$query);

$i = 0;
while($row = mysqli_fetch_assoc($result)){
    if($i == 2) {
    ?>
    <!-- add some html block -->
    <?php
    }
    //display row data
    $i++;
}

如果其他if语句是< 3> 2等,则可以添加其他语句来显示行。

答案 1 :(得分:1)

您可以在一个while循环本身(一个查询)中实现它。使用一个计数器,当计数器达到2时,插入一个html块,然后一会儿继续。

$query = "SELECT * FROM table ORDER BY rand()";
$result = mysqli_query($connection,$query);
$r = 0;
while($row = mysqli_fetch_assoc($result)){

    // your row display code here above the next block

    if (++$r == 2) {
        // now when r is 2, inject that one-time html block
    }
}
相关问题