Php Displaying A Certain Amount Of Records Per Div
Solution 1:
If I got your question right, you want to limit the amount of divs to 3 with PHP. Try adding a LIMIT 3
to your SQL-query:
$stmt = $db->query('SELECT movieID, movieName, movieDesc, movieYear FROM latest ORDER BY movieID DESC LIMIT 3');
I also noticed that there is one echo '<li>';
out of place near the end of your while loop. This may or may not be a problem but I would just delete this if there is not need for it.
Edit: May I have another try?
If I got you right this time, you want PHP to generate any number of <div class="project-list">
with a maximum of 3 <li>
inside each of them, right?
Here you go:
<?phptry {
// this line is for my local setup, you have to change or remove it:$db = new PDO('mysql:host=localhost;dbname=stackmovies;charset=utf8', 'root', '');
$stmt = $db->query('SELECT movieID, movieName, movieDesc, movieYear FROM latest ORDER BY movieID DESC');
$i = 0;
while($row = $stmt->fetch()){
echo"\n"; // for debuggingif ($i % 3 == 0) {
echo'<div class="project-list">';
echo'<ul>';
}
echo"\n"; // for debuggingecho'<li>';
echo'<a href="#" class="no-underline">';
echo'<div class="project">';
echo'<h2 class="project-date">'.$row['movieYear'].'</h2>';
echo'<div class="poster"><img src="assets/img/FoTD_Poster.png" width="160" height="188"></div>';
echo'<h2 class="project-title" align="center"><b>'.$row['movieName'].'</b></h2>';
echo'</a>';
echo'</div>';
echo'</li>';
echo"\n"; // for debuggingif ($i % 3 == 2) {
echo'</ul>';
echo'</div>';
}
echo"\n"; // for debugging$i++;
}
if ($i > 0 && ($i - 1) % 3 != 2) {
echo'</ul>';
echo'</div>';
}
} catch(PDOException $e) {
echo$e->getMessage();
}
?>
Solution 2:
This is the way you want to do it. Harnessing array_chunk()
. You'll need to add all the data from your sql into an array (Which we will call $data
in this example).
while($row = $stmt->fetch()) {
$data[] = $row;
}
Next up, we'll chunk the data up into arrays of 3.
$chunked = array_chunk($data, 3);
And then all you need to do is harness 2 foreach()
loops to print it out as you require.
// start the loop of chunksforeach($chunkedas$chunk) {
// you'd open the row here// get the items in the specific chunkforeach($chunkas$item) {
// you'd find your data elements in $item
}
// you'd close the row off here
}
And here is a working Example
.
Post a Comment for "Php Displaying A Certain Amount Of Records Per Div"