将sql结果排序为3列表的最简单方法是什么?


What's the easiest way to sort my sql results into a 3 column table?

我将包含整个"shopping。php"页面代码这样你就知道我是从哪里来的了

<!DOCTYPE html>
<html>
<head><title>Shopping Page</title>
<style type="text/css">
</style>
<script type="text/javascript">
</script>
</head>
<body> 
    <form name="form1">
    <?php
    if (isset($_GET['cat'])) $cat=$_GET['cat'];
    else $cat = "fx";
    echo $cat;
    //1. Make a connection to the database
    $dbconn = mysqli_connect("localhost","root","","mydatabase1") 
      or die(mysqli_connect_error());
    $sql = "select productid,name,imagefile "
    ."from products "
    ."where categoryid='$cat'";
   echo $sql;

    //2. Run a query against the database
    $result = mysqli_query($dbconn,$sql) 
    or die(mysqli_error($dbconn));

…这是我希望结果作为3列表返回的部分:

//3. Return the results
while ($row = mysqli_fetch_row($result))
{
    echo "<a href='order.php?prod=$row[0]'>$row[1]</a><br>";
    echo "<img src='images/products/$row[2]' "
    ."height=200px width =175px><br>";
}
 //4. Release the resources
 mysqli_free_result($result);
//5. Close the connection
mysqli_close($dbconn);
?>
</form>
</body>
</html>

现在我得到结果,但它只是垂直列出。我尝试了几种不同的方法,但我想我的新手是最好的我。任何帮助都将非常感激。谢谢。

我所看到的是一个两列表,但你应该做一个HTML表。(<br>标签使其垂直)

$count = 0;
echo "<table><tr><th>Name</th><th>Image</th></tr>";
while ($row = mysqli_fetch_row($result))
{
     if($count % 3 == 0){
         echo "<tr>";  //every third image make a new row
     }
     echo "<td><a href='order.php?prod=$row[0]'>$row[1]</a>";
     echo "<img src='images/products/$row[2]' "
     ."height=200px width =175px></td>";
     if($count % 3 == 2){
         echo "</tr>";  //every third image end the row
     }
     $count++;
}
echo "</table>";

请参阅此参考,因为如果您使用mysqli或使用PDO,则应该绑定参数。如何在PHP中防止SQL注入?

回复您的评论

添加了一个计数,每第三个图像添加一个表行标记。%是模运算符,它给你除法的余数。

你可以有很多方法。我认为使用表格是更好的解决方案。但如果你想要最简单的方法就是使用div,使用columns Property来创建column。使用以下样式:

<style>
.column3 {
    -webkit-column-count: 3; /* Chrome, Safari, Opera */
    -moz-column-count: 3; /* Firefox */
    column-count: 3;
}
</style>

div

将结果括起来
<div class="column3">
//Your Result
</div>