I am trying to display lines from a file based on a date range (ex: get today + next 7 days based on date field). I'm not familiar with PHP.
I have the following to read the file and create an array from the contents:
$txt_file = file_get_contents('shipping_dates.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
$info[$row]['Order_Date'] = $row_data[0];
$info[$row]['Free_Shipping'] = $row_data[1];
$info[$row]['Rush_Order'] = $row_data[2];
//display data
echo 'Row ' . $row . ' Order_Date: ' . $info[$row]['Order_Date'] . '<br />';
echo 'Row ' . $row . ' Free_Shipping: ' . $info[$row]['Free_Shipping'] . '<br />';
echo 'Row ' . $row . ' Rush_Order: ' . $info[$row]['Rush_Order'] . '<br />';
}
This works great - Now I need to grab the individual lines based on a date range and display only the lines within the range only, not the entire contents for each of these 3 options.
I would do:
Assuming your desired date range is only for 'entire days' without considering the hours.
Get the date range in unix TimeStamp format. Example for January 2018. You have to manually add " 00:00:00" and " 23:59:59" so you cover the full days.
Before your foreach loop:
$filter_date_from = '2018-01-01';
$filter_date_to = '2018-01-31';
$date_from = $filter_date_from.' 00:00:00'; // add begin of the day
$date_to = $filter_date_to.' 23:59:59'; // add end of the day
$date_from_ts = strtotime($date_from); // convert to unix timestamp
$date_to_ts = strtotime($date_to);
Then inside the loop you would check this, once you have $info[$row]['Order_Date'] stuffed:
// convert the order date to unix timestamp
$order_date_ts = strtotime($info[$row]['Order_Date']);
// just compare
if ($order_date_ts >= $date_from_ts && $order_date_ts <= $date_to_ts) {
// you want the CSV line because it is IN the date range
}
With this solution you don't care if the Order_Date includes hours, minutes and/or seconds, or none of them (strtotime will assume 00:00:00 if none are provided).
Please note that the dates/datetimes must be in a format that the php function "strtotime" understands, like Y-m-d. See documentation for strtotime if you get weird results.
Not tested but let me know if it works for you...
Related
I want to add particular days to current date. where days are taking from database field. It adds to the present date properly but at next day, date is going to update to the present date again.so how to keep date unchanged. It should take only once in PHP
$day= $cur["Days"];
if(($cur["Days"]) == 0){
$new = '';
} else {
$Date = date('20y-m-d');
$new = date("20y-m-d", strtotime($Date . ' + ' . $day . ' days'));
}
input if $day=1,$day+$new
output= jan19,this is the output of one row and my problem is it should remain as it is for this row but now for next day it is going to change to jan20 that should not happen
I created a chat application in PHP and jQuery. The messages are stored into a database with a UNIX timestamp as post date.
Now I want to list each message sorted by day, but as you can see in the image it insert the day-divider twice while both messages are posted on the same day (Tuesday December 15, 2015). So this is wrong.
Does somebody knows how to fix this?
$messages = $result->fetch_assoc();
// Get the very first post-date in a UNIX timestamp
$previousDate = $messages['postTime'];
mysqli_data_seek($result, 0);
$data = '';
while ($aMessages = $result->fetch_assoc())
{
if ($previousDate <= $aMessages['postTime'])
{
// Create a new day-divider when a new day is reached.
$data .= '<span>' . date("l F d, Y", $aMessages['postTime']) . '</span>';
}
$data .= $aMessages['message_text'];
$previousDate = $aMessages['postTime'];
}
The operator must be minor instead minor or equal:
if ($previousDate < $aMessages['postTime'])
EDIT
A Unix timestamp is expressed in seconds, two dates in the same day may have different number of seconds. Try this:
if (date('Y-m-d', $previousDate) < date('Y-m-d', $aMessages['postTime']) )
I am trying to add days and/or weeks to a date that is being pulled from a database. All I am getting is the 12-31-1969 default date when it cannot output correctly. Here is my code:
$lastFeed = "6-25-2013"; //pulled from database last feed date
$feedSchedule = "2"; //pulled from database number of weeks.
$nextFeeding = date("m-d-Y", strtotime($lastFeed . ' + ' . $feedSchedule. ' week'));
I have also tried multiplying the days times the $feedSchedule variable and replacing week(s) with day(s).
6-25-2013 is not a valid date format. Try YYYY-MM-DD
Here is code that will work and account for the invalid Date Time String
function nextFeeding($lastFeed,$feedSchedule){
//fix date format
$correctedDate = explode("-",$lastFeed);
//pad month to two digits may need to do this with day also
if($correctedDate[0] < 10 && strlen($correctedDate[0])!==2){
$correctedDate[0] = "0".$correctedDate[0];
}
$correctedDate = $correctedDate[2]."-".$correctedDate[0]."-".$correctedDate[1];
//get the next feeding date
$nextFeeding = date("m-d-Y", strtotime($correctedDate . ' + ' . $feedSchedule. ' week'));
//return value
return $nextFeeding;
}
$lastFeed = "6-25-2013"; //pulled from database last feed date
$feedSchedule = "2"; //pulled from database number of weeks.
$nextFeeding = nextFeeding($lastFeed,$feedSchedule);
echo $nextFeeding;
returns
07-09-2013
I have a table called schedule and a column called Date where the column type is date. In that column I have a range of dates, which is currently from 2012-11-01 to 2012-11-30. I have a small form where the user can enter a range of dates (input names from and to) and I want to be able to compare the range of dates with the dates currently in the database.
This is what I have:
////////////////////////////////////////////////////////
//////First set the date range that we want to use//////
////////////////////////////////////////////////////////
if(isset($_POST['from']) && ($_POST['from'] != NULL))
{
$startDate = $_POST['from'];
}
else
{
//Default date is Today
$startDate = date("Y-m-d");
}
if(isset($_POST['to']) && ($_POST['to'] != NULL))
{
$endDate = $_POST['to'];
}
else
{
//Default day is one month from today
$endDate = date("Y-m-d", strtotime("+1 month"));
}
//////////////////////////////////////////////////////////////////////////////////////
//////Next calculate the total amount of days selected above to use as a limiter//////
//////////////////////////////////////////////////////////////////////////////////////
$dayStart = strtotime($startDate);
$dayEnd = strtotime($endDate);
$total_days = abs($dayEnd - $dayStart) / 86400 +1;
echo "Start Date: " . $startDate . "<br>End Date: " . $endDate . "<br>";
echo "Day Start: " . $dayStart . "<br>Day End: " . $dayEnd . "<br>";
echo "Total Days: " . $total_days . "<br>";
////////////////////////////////////////////////////////////////////////////////////
//////Then we're going to see if the dates selected are in the schedule table//////
////////////////////////////////////////////////////////////////////////////////////
//Select all of the dates currently in the schedule table between the range selected.
$sql = ("SELECT Date FROM schedule WHERE Date BETWEEN '$startDate' AND '$endDate' LIMIT $total_days");
//Run a check on the query to make sure it worked. If it failed then print the error.
if(!$result_date_query = $mysqli->query($sql))
{
die('There was an error getting the dates from the schedule table [' . $mysqli->error . ']');
}
//Set the dates to an array for future use.
// $current_dates = $result_date_query->fetch_assoc();
//Loop through the results while a result is being returned.
while($row = $result_date_query->fetch_assoc())
{
echo "Row: " . $row['Date'] . "<br>";
echo "Start day: " . date('Y-m-d', $dayStart) . "<br>";
//Set this loop to add 1 day to the Start Date until it reaches the End Date
for($i = $dayStart; $i <= $dayEnd; $i = strtotime('+1 day', $i))
{
$date = date('Y-m-d',$i);
echo "Loop Start day: " . date('Y-m-d', $dayStart) . "<br>";
//Run a check to see if any of the dates selected are in the schedule table.
if($row['Date'] != $date)
{
echo "Current Date: " . $row['Date'] . "<br>";
echo "Date: " . $date . "<br>";
echo "It appears as though you've selected some dates that are not in the schedule database.<br>Please correct the issue and try again.";
return;
}
}
}
//Free the result so something else can use it.
$result_date_query->free();
As you can see I've added in some echo statements so I can see what is being produced. From what I can see it looks like my $row['Date'] is not incrementing and staying at the same date. I originally had it set to a variable (currently commented out) but I thought that could be causing problems.
I have created the table with dates ranging from 2012-11-01 to 2012-11-15 for testing and entered all of this php code onto phpfiddle.org but I can't get the username provided to connect.
Here is the link: PHP Fiddle
I'll be reading through the documentation to try and figure out the user connection problem in the meantime, I would really appreciate any direction or advice you can give me.
I have a tricky one here.
I have a number of results in a table, this table has id, market, date and points.
I want to get all the records for a given month and then output all the points for each day, in order.
I'm not sure of the best way to do this? Her are my options, well my ideas, I could set a loop that will execute for every day of the given month, this will run a query to find every record for that day and will do this for every day of the month, this will then be easy to order a format the records but i'm thinking its not a good idea to query the database that many times.
The second idea i to query the database for all the records for that date, order them by the date. However i can see come problems here when outputting the information for each day, well it will be a long job then the first i think.
Any ideas? anyone done something like this before and could lend a helping hand? Any advise would be more than welcome!
Thanks.
while($row = mysql_fetch_array($getresults))
{
$day = FALSE;
foreach ($row as $row)
{
$day_res = date("Y-m-d H:m:s", strtotime($row["date"]));
if (!$day || $day != $day_res)
{
$day = $day_res;
echo '<h1>'.$day.'</h1>';
}
echo $row['date'] . " " . $row["id"] . ": " . $row["market"] .
"/" . $row["points"] . "<br/>";
}
}
This is the output i get from it:
1970-01-01 00:01:00
3 3: 3/3
3 3: 3/3
2012-01-13 09:01:06
E E: E/E
E E: E/E
1970-01-01 00:01:00
2 2: 2/2
2 2: 2/2
- -: -/-
- -: -/-
1970-01-01 00:01:00
4 4: 4/4
4 4: 4/4
and that more or less repeats for a while.
Thanks again.
If that date is only a date, then you could try something like this:
SELECT t.date, SUM(t.points) FROM table t WHERE date BETWEEN [STARTDATE HERE] AND [ENDDATE HERE] GROUP BY t.date
What it does? It selects everything the date & the sum of the points of that day, because we group all the results based on a day. So for every unique date in your table you will get a row with a result. Use the WHERE date statement to define from which month you need the selection.
Addition: the thing shown is only valid if date is in format like: YYYY-MM-DD. In case you have a timestamp (YYYY-MM-DD HH:ii:ss) you could try to change the query to:
SELECT t.date, SUM(t.points) FROM table t WHERE date BETWEEN [STARTDATE HERE] AND [ENDDATE HERE] GROUP BY DAYOFMONTH(t.date)
This ensures that you will group them by the day of the month (1 to 31) based on the dates from your table.
at first the query to get all for a given month ordered by date:
SELECT * FROM `table` WHERE `date` LIKE '2012-01%' ORDER BY date;
here the php loop to show it:
$day = FALSE;
foreach ($results as $result){
$day_res = date("d", strtotime($result["date"]));
if (!$day || $day != $day_res){
$day = $day_res;
echo '<h1>'.$day.'</h1>';
}
echo $result["id"].": ".$result["market"]."/".$result["points"]."<br/>";
}
Ok here for your structure:
$day = FALSE;
while($row = mysql_fetch_array($getresults))
{
$day_res = date("Y-m-d H:m:s", strtotime($row["date"]));
if (!$day || $day != $day_res)
{
$day = $day_res;
echo '<h1>'.$day.'</h1>';
}
echo $row['date'] . " " . $row["id"] . ": " . $row["market"] .
"/" . $row["points"] . "<br/>";
}