使用PHP显示mySQL结果的顺序

时间:2017-10-07 14:51:29

标签: php mysql

        <div class="container-fluid projects-container">
            <div class="container projects-list">
<?php
$servername = "localhost";
$username = "user_showcase";
$password = "password123";
$dbname = "data_showcase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, name, description, link, date, image, size, picid FROM projects";
$result = $conn->query($sql);

        if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo " <div class='col-md-6 box' id='".$row["id"]."'><div class='project'><div class='image blurry' id='".$row["picid"]."' style='background: url(http://www.all-channels.com/projects/images/".$row["image"].") top center no-repeat;'></div><div class='description-small'>

        <h6>".$row["date"]."</h6> 
        <h2>". $row["name"]. "</h2>
        <p>". $row["description"]. "</p>        
        <a href=" . $row["link"] . " target='_blank' class='go'>Take a look</a></div></div></div> ";
    }
} else {
    echo "0 results";
}
                $conn->close();
?>

            </div>
        </div>

需要一种方法在序列中的bootstrap div中显示来自mySQL数据库的信息:

  1. 表格的第一行和第二行将显示在两个相邻的div中,类别为 col-md-6
  2. 第三行显示在另一个div中,类 col-md-12
  3. 然后col-md-12之后的下两行信息将再次显示在两个col-md-6中,第六个显示为col-md-12。
  4. 我已经制作了在宽度相等的列中回显所有结果的代码。 只是不知道如何使它以所需的顺序以不同的宽度div显示它们。

1 个答案:

答案 0 :(得分:0)

实现这一目标的最简单方法

$counter = 1;
while($row = $result->fetch_assoc()){
    /* If any particular pattern by which you will get to know whether the code is gonna go in 2 columns (col-md-6) or 1 column (col-md-12) */
    /* Based on your code pattern if the loop in divisible by 3 then its col-md-12 else its col-md-6. The following code does the trick for you */
    $columnCondition = ($counter % 3 == 0) ? 'col12' : 'col6';  
    switch($columnCondition){
        case 'col6':
            echo '<div class="col-md-6">';
                //Row value
            echo '</div>';
            break;

        case 'col12':
            echo '<div class="col-md-12">';
                //Row value
            echo '</div>';
            break;
    }
    $counter++;
}