I want to select every photo from my database, then display them grouped by month. I have that code here:
<?php
if (isset($_COOKIE['user_id'])) {
if (!isset($_GET['user_id'])) {
$user_id= $_COOKIE['user_id'];
} else {
$user_id= $_GET['user_id'];
}
$connect= mysqli_connect("localhost", "root", "", "si");
$query= "SELECT * FROM posts WHERE user_id= $user_id ORDER BY date DESC";
$result= mysqli_query($connect, $query)
or die('error with query');
$date = "0";
while ($row= mysqli_fetch_array($result)) {
if ($date != $row['date']) {
echo "<p> ".$row['date']."</p><br/>";
$date = $row['date'];
}
echo '<img src="'.$row['picture']. '"/>' . "<br/>";
}
}
?>
The only problem is that my code displays EVERY image from each month, this makes for an excessively large page. I want to limit my results to only 8 per month (or less if there isn't event 8 pictures for that month), then display a "show more..." link if there are more than 8. I know how to add a LIMIT to my initial query, but that won't work for this scenario. What can I do?
Here is how I want it to look:
add LIMIT $start, $numToDisplay
to your SQL statement, and use PHP to calculate the new values for the $start
variable.
eg $pageNum = $_GET["page"]
and 8 images per page means you can calculate that:
$numToDisplay = 8;
$start = ($pageNum-1)*$numToDisplay;
What you need to do is monitor picture count
$pickLimit = array ();
while ( $row = mysqli_fetch_array ( $result ) ) {
if ($date != $row ['date']) {
echo "<p> " . $row ['date'] . "</p><br/>";
$date = $row ['date'];
}
$pickLimit [$date] = isset ( $pickLimit [$date] ) ? $pickLimit [$date] : 0;
if ($pickLimit [$date] > 7)
continue;
echo '<img src="' . $row ['picture'] . '"/>' . "<br/>";
$pickLimit [$date] ++;
}
This could be easily done using the php script whitch you already have and some css tricks, that are also used for creating an animated slider/carousel. Something like this:
<div id="carousel">
<div id="slider">
<?php foreach($images as $img) { ?>
<div class="image">
<img src="<?php echo $img; ?>" />
</div>
<?php } ?>
</div>
</div>
As for the css:
#carousel {
width: 900px; /* how much you need */
height: 100px; /* how much you need */
overflow: hidden;
}
#slider {
width: auto;
height: 100px;
}
.image {
float: left;
}
This is what is known as "greatest n per group" query. If you search on here there are many examples with different solutions. Here is one of them -
SELECT *
FROM (
SELECT
tmp.*,
@r := IF(@m=DATE_FORMAT(`date`, '%Y%m'), @rank + 1, 1) rank,
@m := DATE_FORMAT(`date`, '%Y%m')
FROM (
SELECT *
FROM posts
WHERE user_id = $user_id
ORDER BY date DESC
) tmp, (SELECT @m:=NULL, @r:=NULL) initvars
) tmp2
WHERE rank <= 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.