循环遍历PHP PHP mysql

时间:2016-04-04 15:13:04

标签: php mysql

我能够从Mysql数据库中检索数据,但每4列我需要关闭行和开始和新行 以下是我的HTML代码,我试图循环遍历列,并在每4列关闭行后继续添加数据库中的列。 enter image description here

这是我的代码(我知道这不是PDO,我正在努力学习,所以我可以转换为PDO MySQLi连接)

 <div class="row">
    <div class="row margin-bottom-20">

    <?php
       include('dbconnect.php');
       $query = "SELECT * FROM selection"; 
       mysql_set_charset("UTF8");
       $result = mysql_query($query) or die(mysql_error());

    for($i=1; $row = mysql_fetch_array($result); $i++){
    ?>
             <div class="col-md-3">

                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title"><i class="fa fa-tasks"></i> <strong><?php echo $row['Title']; ?></strong></h3>
                        </div>
                        <div class="panel-body">

                          <p>
                             <?php echo $row['ContactInfo']; ?><br/>
                             <img class="img-responsive" src="http://myurl.com/selections/<?php echo $row['file_url']; ?>" >
                          </p>
                        </div>
                    </div>

                </div>


             <?php
                }
             ?>  

我需要添加一个新的for循环,但到目前为止我还没有成功。谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

if($i%4==0)
{
    //close the existing div and start new row div here
}

这将在每4次迭代后开始一个新行

答案 1 :(得分:0)

试试这个

<?php
include('dbconnect.php');
$query = "SELECT * FROM selection"; 
mysql_set_charset("UTF8");
$res = mysql_query($query) or die(mysql_error());

while($rows = mysql_fetch_array($res)){
    $result[] = $rows;
}

$array = array_chunk($result, 4);

foreach ($array as $value) {
    foreach ($value as $row){
         ?>
        <div class="col-md-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><i class="fa fa-tasks"></i> <strong><?php echo $row['Title']; ?></strong></h3>
                </div>
                <div class="panel-body">
                    <p>
                        <?php echo $row['ContactInfo']; ?><br/>
                        <img class="img-responsive" src="http://myurl.com/selections/<?php echo $row['file_url']; ?>" >
                    </p>
                </div>
            </div>
        </div>                      
<?php 
    }
}