I'm having some problems with the php script below that I'm currently working on. What I am trying to do is make a list with 5 events that are being shown ordered by date. In my database I have a table with events. Each event has a date (DATETIME), an id and a name. What the php needs to do is check the table with events and filter the ones that have already passed. If an event has already passed, it's not shown. If it still has to happen, it's shown.
Now the problem is that in the do while loop, the script doesn't seem to go to a next row when it has had a run. For example: if the database table has 10 events in it, it will show 10 times the event that's on the first row of the table when testing.
I need to know what I'm doing wrong, or if there is a way to make the row increase after each run of the loop.
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
do{
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{ //if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
} while(($i <= 4) && ($rij_kalender = mysql_fetch_assoc($test_result_kalender)));开发者_StackOverflow社区
echo "<p>While loop finished</p>"; //just some checking
?>
Your code loads the date once and then compares it to today each time. Move
$datum_unix = strtotime($rij_kalender['datum']);
into the loop, before the date check.
Try this:
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
while($rij_kalender = mysql_fetch_assoc($test_result_kalender))
{
$datum_unix = strtotime($rij_kalender['datum']);
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{
//if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
if ($i == 5) break;
}
echo "<p>While loop finished</p>"; //just some checking
?>
精彩评论