I got a script for displaying data from db who display one next to the other. I want to know how to limit the data to 4 by line so the next one will be display on another line.
Here is my code:
<?php
if ($connexion) {
// Effectuer la requête
$query = "SELECT * FROM asset_Services";
$result = mysqli_query($connexion, $query);
echo '<ul id="list">';
// Afficher les lignes du tableau en fonction de la réponse à la requête
if ($result) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li><h5 style="margin-top:20px">'.$row["nom"].'</h5><br></li>';
}
}
echo '</ul>';
}
?>
2
Answers
You just need to have a variable which is always incremented modulo 4 and when it reaches a period, have a newline:
EDIT
Even though the question was not tagged as a CSS question, the default behavior is to already have newlines between
li
items, so if that’s not solved, you will need to handle yourself. Example:Note that I removed the
h5
elements, because they were botching up the styling.You can try this
Explanation:
1 – I added a $counter variable to keep track of the number of items displayed.
2 – Inside the loop, I check if the counter is divisible by 4 (
$counter % 4 === 0
). If true, it means 4 items have been displayed, and a new line is started using a<div style="clear:both;"></div>
to clear the floats.3 – Each list item (
<li>
) is given a style (float:left; width: 25%;
) to ensure that they float next to each other and take up 25% of the width to fit 4 items in a row. Adjust the width as needed based on your layout.This should display your data in groups of 4 per line. Adjust the styles and structure based on your specific needs.