希望在表格的每一行中显示3条记录为三列

时间:2017-12-25 16:52:50

标签: php mysql

我有一个包含3列的表。 Sql1查询从数据库中获取商店名称,只显示第1列中的所有商店,但我想在3列中每行显示3条记录。即第1行中的前3条记录,第2条中的后3条记录,依此类推。如果我尝试使用偏移它也有固定号码,所以它没有帮助。请帮助。谢谢提前

<style>
.vertical-menu {
     overflow-y: auto;
     float: left;
     position: fixed;
     width: 15%;
     left: 0;
     top: 9%;
bottom: 0;}
.header {
  background-color: #327a81;
  color: white;
  font-size: 1.5em;
  padding: 1rem;
  text-align: center;
  text-transform: uppercase;}
.vertical-menu a {
    background-color: #eee;
    color: black;
    display: block;
    padding: 12px;
    text-decoration: none;}
.vertical-menu a:hover {
    background-color: #4CAF50;}
.vertical-menu a.active {
    background-color: #4CAF50;
    color: white;
}</style></head>
<body>
<?php 
$con=mysql_connect('localhost','root','')or die(mysql_error());
$db=mysql_select_db('shop',$con) or die(mysql_error());
$sql='Select id,name from info';
$retrieval = mysql_query($sql,$con);

if(!$retrieval) {
    die('Could not get data'.mysql_error());
}

$id=$_GET['name'];
 echo "<div class='vertical-menu' >


<a href='#'>Dashboard</a>
<a href='#'>ShopList</a>
 ";
while ($row=mysql_fetch_array($retrieval, MYSQL_ASSOC)) {
}
echo "</div>";

$sql1="Select name from info limit 3 offset 1";
$retrieval1 = mysql_query($sql1,$con);

if(!$retrieval1) { 
    die('Could not get data'.mysql_error());
}
?>
<div class="col-xs-5 col-sm-5 col-md-5 col-lg-9 col-lg-offset-2"  style="margin-top: 5%;left:4%; ">
            <div class="header">List</div>
    <table  class="table table-striped">
    <thead><tr>
        <th>Shop Name</th>
        <th>Shop Name</th>
        <th>Shop Name</th>
    </tr></thead>
    <?php
while ($row1=mysql_fetch_array($retrieval1, MYSQL_ASSOC)) {
?>
 <tbody><tr>
<td><a href="#"><?php echo $row1['name']; ?></a></td>
         </tr></tbody>                           
    </div>
<?php}?>
 </table>

1 个答案:

答案 0 :(得分:0)

试试这个:

<table  class="table table-striped">
<tr>
    <th>Shop Name</th>
    <th>Shop Name</th>
    <th>Shop Name</th>
</tr>

<?php

    $counter = 0;
    $emptyColumns = false;

    while ($row1=mysql_fetch_array($retrieval1, MYSQL_ASSOC))
    {
        // In the beginning and at every count of 3 write a <tr>
        if($counter == 0 || $counter % 3 == 0)
        {
            echo '<tr>';
        }

        // Write <td> every time
        echo '<td><a href="#">'.$row1['name'].'</a></td>';
        // Increment counter
        $counter++;

        // At every count of 3 write a </tr>
        if($counter % 3 == 0) 
        {
            echo '</tr>';
        }
    }

    // If table is not full (some columns left empty)
    if($counter % 3 != 0) $emptyColumns = true;

    // Fill empty columns
    while($counter % 3 != 0)
    {
        $counter++;
        echo '<td><a href="#">Empty</a></td>';
    }

    // If there were empty columns that means the </tr> tag was not written
    if($emptyColumns)
    {
        echo '</tr>';
    }

    echo '</table>';
?>