在创建while循环时遇到问题

时间:2017-01-18 14:24:42

标签: php html css mysql while-loop

我已经编写了两个列布局的CSS,我有一个"用户"带有用户注释的数据库。

所以当我像这样运行一个while循环时: while($ row = mysqli_fetch_array($ result))

PHP应该像这样动态创建html(取决于用户数量):

    <div class="row">

        <div class="col">
            <div class="col-content"><?php echo $row['notes'] ?></div> 
            <!-- Notes of user 1 -->
        </div>

        <div class="col">
           <div class="col-content"><?php echo $row['notes'] ?></div>
           <!-- Notes of user 2 -->
        </div>

    </div>

    <div class="row">

          <div class="col">
               <div class="col-content"><?php echo $row['notes'] ?></div>
               <!-- Notes of user 3 -->
           </div>

           <div class="col">
              <div class="col-content"><?php echo $row['notes'] ?></div>
              <!-- Notes of user 4 -->
           </div>

    </div>

如果只有一个用户,html应该是这样的:

<div class="row">

    <div class="col">
        <div class="col-content"><?php echo $row['notes'] ?></div>
        <!-- Notes of user 1 -->
    </div>

</div>

同样,如果有3个用户,则应该有一行有两列,另一行有一列。

有没有办法做到这一点?

编辑:在这里添加了我的PHP代码。

   <?php 

    $query = "SELECT * FROM users"; 
    $result = mysqli_query($conn, $query);
    while($row = mysqli_fetch_array($result)){

   ?>

    <div class="row">

        <div class="col">
            <div class="col-content"><?php echo $row['notes'] ?></div>
        </div>

    </div>


   <?php  } ?>

该代码存在的问题是它使用&#34;一列&#34;创建了一个新行。为每个用户。我的目标是拥有两列#34;在行中。

2 个答案:

答案 0 :(得分:1)

你可以用循环中的模运算符(%)来实现类似的东西。

$i = 0;
$rowCount = mysqli_num_rows($result);
$rowsHTML = '';

while($row = mysqli_fetch_array($result)){
    $notesHTML = '<div class="col">
            <div class="col-content">'.$row['notes'].'</div> 
            <!-- Notes of user 1 -->
        </div>';

    if($i%2 == 0){
        $notesHTML = '<div class="row">'.$notesHTML;
        // check if its the last item and the row has to be closed after 1 col
        if($i+1 == $rowCount){
            $notesHTML = $notesHTML.'</div>';
        }
    } else {
        $notesHTML = $notesHTML.'</div>';
    }

    $rowsHTML .= $notesHTML;
    $i++;
}
echo $rowsHTML;

答案 1 :(得分:1)

<?php

$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
$i = 0;

?>

<div class="row">

<?php 

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

    if($i>1 && $i%2==0) echo '</div><div class="row">';

    $i++;
?>
    <div class="col">
        <div class="col-content"><?php echo $row['notes'] ?></div>
    </div>

<?php  } ?>

</div>