[英]Organizing database list into columns using PHP
我的SQL數據庫有很多行。 我使用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解決方案在下面!
嘗試將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>";
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.