我的sql db有很多行。我使用php while循环来回显页面上的数据库,进入html列表
<ul>
<?php
while ($data = mysqli_fetch_assoc($result)):
$address = $data['address'];
$ad_link = $data['ad_link'];
if(is_null($ad_link)){$ad_link = "#";}
?>
<li><?php echo $address; ?></li>
<?php endwhile; mysqli_close($con); ?>
</ul>
我希望列表在吐出一定数量的行之后进入相邻的列(而不是只在页面上运行一英里)。
然后进入第三和第四列。
如何开始这样做?最好在表格中进行。
下面的@lance解决方案!
答案 0 :(得分:2)
尝试将您的MySQL代码与PHP / HTML代码分开,因为它可能会让您感到困惑。如果要回显多个列表,则在每个列表中定义所需的列表项数,然后创建两个循环;一个用于回显列表的实际开始和结束标记,一个用于列表项。列表项循环将需要嵌套在另一个循环内。
<?php
// Connect to the DB
$mysqli = mysqli_connect('localhost', 'username', 'password', 'db_name');
if(mysqli_connect_errno($mysqli)) {
echo mysqli_connect_error($mysqli);
die;
}
$sql = "SELECT * FROM table";
$query = mysqli_query($mysqli, $sql)or die(mysqli_error($mysqli));
$num = mysqli_num_rows($query);
$i = 0;
while($row = mysqli_fetch_array($query)) {
$address[$i] = $row['address'];
$ad_link[$i] = $row['ad_link'];
$i++;
}
mysqli_close($mysqli);
// Define how many list items will be placed in each list
$per_list = 10;
// Determine how many lists there will need to be
$lists = ceil($num/$per_list);
// Loop thru each list
for($i=0;$i<$lists;$i++) {
echo "<ul style='float:left;'>";
// Determine the starting and ending points for the second loop that will echo out the list items
$start = $i*$per_list;
// Since the final list may not be a complete list containing 10 items,
// only extend the loop to the full amount
if($i == ($lists-1)) {
// Find the modulus
$mod = $num%$per_list;
if($mod > 0) {
$end = ($start+$per_list)-$mod;
} else {
$end = $start+$per_list;
}
} else {
$end = $start+$per_list;
}
// Echo out the list items that are inside of the list
for($x=$start;$x<$end;$x++) {
if(is_null($ad_link[$x])) {
$ad_link = "#";
}
echo "<li>".$address[$x]."</li>";
}
echo "</ul>";
}
echo "<div style='clear:both;'></div>";
?>