Reputation: 569
My sql db has many rows. I use a php while loop to echo out the database on a page, into a html list
<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>
I would like the list to run into an adjacent column after a certain number of lines have been spit out (rather than just run a mile down the page).
Then going into a third and forth column.
How does one even begin to do this? Doing it in a table would be preferable.
@lance solution below!
Upvotes: 0
Views: 141
Reputation: 4820
Try separating your MySQL code from your PHP/HTML code as it can get confusing. If you want to echo out multiple lists, then define how many list items that you want in each list and then create two loops; one to echo out the actual opening and closing tags for the lists and one for the list items. The list items loop will need to be nested inside of the other loop.
<?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>";
?>
Upvotes: 2