2

I am new to php and mysql programing and I have a question in working with the date.

There is a date field that stores the date in the table

eg 2013-05-27, 2013-05-24, 2013-05-22

I need to retrieve the latest 3 days data for further processing, first is locate today's date, if cannot find, then will locate yesterday's data, if cannot find, then locate the date before yesterday's data etc. Then I have the below code:

$date1=date('Y-m-d');
$date1_1="";
$datefound="";
while( $datefound <> ""){
    $date1_1_1 = mysql_query("SELECT * FROM jom_c1 where date ='" .$date1. "'");
    if($date1_1_1){
    $datefound = $date1;
}else{
    $date1 = date('Y-m-d', strtotime($date . ' - 1 day'));
}
}
echo $datefound; 
?>

however, it seems like the loop is not running, much appreciated if someone can give me a hints with it.

3 Answers 3

5

You may want to consider using SQL properly, ie

select * from jom_c1 where date <= curdate() order by date desc limit 3

rather than looping.

(Your loop doesn't run much, because as soon as date is found, it stops)

Sign up to request clarification or add additional context in comments.

1 Comment

@Mifeet Possibly not. I've added an explicit sort
0

The reason that the while block is not executing is that you set $datefound="" but your condition is while ($datefound<>"").

Comments

0

If you're looking for the most current date that has a record in jom_c1, then try the following query:

SELECT * FROM jom_c1 WHERE date <= CURDATE() ORDER BY date DESC LIMIT 1

If you're looking for the latest three dates, then use LIMIT 3 instead of LIMIT 1.

The PHP code would look like this:

$datefound = "";
$result = mysql_query('SELECT * FROM jom_c1 WHERE date <= CURDATE() ORDER BY date DESC LIMIT 1');
if ($result && mysql_num_rows($result) > 0) {
    $row = mysql_fetch_assoc($result);
    $datefound = $row['date'];
}
echo $datefound;

Note that mysql_query is deprecated, however.


Edit: If there are multiple records for one day, then use the following query:

SELECT DISTINCT date FROM jom_c1 WHERE date <= CURDATE() ORDER BY date DESC LIMIT 1

Distinct will leave out duplicate records.

2 Comments

thank you very much for your help, i have tried. But one thing, we have 16 records in one day, can i group to just store 1 record in the array with the same "date" ?
thank you very much again, i have tried it but with LIMIT 3, then it only show 2 records Array ( [date] => 2013-05-22 ) Array ( [date] => 2013-05-21 ) it should have a 2013-05-23. have i done something wrong ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.