I have a piece of code that will display the results and comparisons of a number(3) of database queries in a browser. It displays the differences in the figures of each DB. It works and that is all okay. Now, what I have to do is forget about the webpage and have the php script run once a day, say at 3am, and the script has to look for any difference in the DB figures for the previous day. If any differences are discovered, using Amazon Simple Notifications Service, an email will be sent to all the subscribers with the details those differences. Here is the part of my code that is new from the previous working script (the one for the browser):
if ($total_results) {
foreach ($total_results as $cid => $dates) {
foreach($dates as $row) {
$dbOne_total = $row['dbOne_total'];
$dbTwo_total = $row['dbTwo_total'];
$dbThree_total = $row['dbThree_total'];
$difference = ($dbTwo_total - $dbOne_total);
$difference_bill = ($dbThree_total - $dbOne_total);
$mismatchFile = fopen("mismatch.txt", "w");
$issue = "";
while($startDate == date('Y-m-d', strtotime('-1 day'))) {
if (($difference_bill > 0) || ($difference > 0)) {
$issue = ($row["company"] ." ". $row["company_id"]. " ". "dbTwo Difference". " ". $difference. " "."dbThree Difference". " ". $difference_bill);
print_r($issue);
topic("DATABASE-MISMATCH")->send("List of mismatches between databases", "Issue: $issue/n"); // for ASN
}
}
fwrite($mismatchFile, $issue);
fclose($mismatchFile);
}
}
$startDate is a variable I am using throughout the code as I have sql queries running that need this date to get the info.
I'm questioning this line:
while($startDate == date('Y-m-d', strtotime('-1 day'))) {
I'm not sure if strtotime is the best option (I'm worried about possible format issues). Is there a better way to get the data from the previous day?
I'm wondering if I am approaching this problem in the correct way? I would also appreciate any advice on how to the $issue variable into the Amazon SNS email body, as a list, or would it be better to create a file and send that as an attachment?
I am still quite a newbie to PHP and so any assistance, or a helpful point in the right direction, would be so much appreciated.
while($startDate == date('Y-m-d', strtotime('-1 day'))) is a wrong approach. It always returns true and the cycle is infinite.
If you want just a one time day before, use
$date = new \DateTime('now - 1 day');
echo $date->format('Y-m-d');
If you need to do it in a loop
$date = new \DateTime(); // now here
for($i = 1; $i <= 10; $i++) {
$date->sub(new \DateInterval('P' . $i . 'D'); // $i days before, $i>0
}
Related
Gooooood evening all...
Edit:
I'm trying to write a php script to output the dates I will work for the remainder of the year if given a specific start date.
For example I start on 2020-05-14 and work for 4 days then take 4 days off.
This continues for the remainder of the year.
I would like to output the dates i will work and think it could probably be done using the php for loop, however i've been thinking of how to do this for too long and can't seem to break through the wall.
The start of my code is this:
<?php
$z = date("z",mktime(0,0,0,05,14,2020));
for($i=$z;$i<=365;$i+=4) {
echo("$i<br>");
}
?>
Any advice would be much appreciated on a possible solution.
You're computing the day of the year (e.g. for 2020-05-14, that would be 134), which is fine for letting your script know when to stop.
However, you're wanting to output dates, where you're currently outputting the day of the year instead.
I think there's an easier way to do what you're trying to accomplish.
<?php
$start = new \DateTime("2020-05-14 00:00:00");
$end = new \DateTime($start->format("Y") . "-12-31 00:00:00");
$four = new \DateInterval("P4D");
$one = new \DateInterval("P1D");
$format = 'Y-m-d';
$date = $start;
while ($date <= $end) {
echo $date->format($format), PHP_EOL;
for ($day = 2; $day <= 4; $day++) {
$date->add($one);
echo $date->format($format), PHP_EOL;
}
$date->add($four);
}
In my database I use CURRENT_TIMESTAMP to keep track of the registration dates for my new users.
Now I wish to generate a list of users who signed up in the past 7 or 30 days.
I figured it would be as simple as explained in this topic;
Get 30 days back date along with time
But my current code generates an unexpected output.
for($i = 0; $i < $userlenght; $i++){
$comparedate = strtotime(date('Y-m-d', $user[$i]["date"]));
echo $comparedate . "<br/>";
if($user[$i]["date"] > $last){
//do stuff here with the users who match.
}
}
This displays the $comparedate value as "-3600" and I have no idea why.
Can anyone provide some insight?
SQL Timestamp is returned formatted as a string, so you need to instruct PHP to read the string as a date formatted value. To do so you need to use strtotime().
Try the following:
for($i = 0; $i < $userlenght; $i++){
$comparedate = strtotime(date('Y-m-d', strtotime($user[$i]["date"])));
echo $comparedate . "<br/>";
if($user[$i]["date"] > $last){
//do stuff here with the users who match.
}
}
Your problem is that $user[$i]['date'] is a MySQL Timestamp which looks like 2018-09-14 11:09:10, and is not a valid input to date. You can just remove the call to date and your code should work fine:
$comparedate = strtotime($user[$i]["date"]);
I want to loop a date so that every time date is increment by previous date. my code is here. plz reply anyone, thanks in advance
$today = date('Y-m-d');
for($i=1; $i<=4; $i++){
$repeat = strtotime("+2 day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
I want result as if today is 2016-04-04 than, 2016-04-06, 2016-04-08, 2016-04-10, 2016-04-12.
actually i want to make a reminder date where user enter reminder. lets a user want to add reminder today and want repeat it 5 time after 2days, 3days or what ever he wants, in next comming day. than how i repeat date with for loop.
Try this:
<?php
$today = date('Y-m-d');
for($i=1; $i<=4; $i++)
{
$repeat = strtotime("+2 day",strtotime($today));
$today = date('Y-m-d',$repeat);
echo $today;
}
Output:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
The easiest way is what answer
aslawin
The below example is to go through the date
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$step = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $step, $end);
foreach ($period as $dt)
{
<sample code here>
}
You can try this:
$today = date('Y-m-d');
for($i=1; $i<=8; $i++){
if($i%2 == 0){
$repeat = strtotime("+$i day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
In this example, you can use $i%2 == 0 with limit <= 8
Use a for loop with base 2, then directly output your dates:
for( $i=2; $i<9; $i=$i+2 )
{
echo date('Y-m-d', strtotime( "+ $i days" )) . PHP_EOL;
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
actually i want to make a reminder date where user enter reminder.
lets a user want to add reminder today and want repeat it 5 time after
2days, 3days or what ever he wants, in next comming day. than how i
repeat date with for loop.
I'll help with the above. First of all I will just say I have a huge personal preference towards the DateTime object over simply using date it's more flexible and a hell of a lot more readable in my opinion, so when working with dates I would always suggest using that over date()
So here is some Code:
$date = new DateTime(); // Pretend this is what the User entered. We got it via $_POST or something.
$interval = 2; // Repeat x times at y day intervals. (Not including the initial)
$repeatAmount = 2; // Repeat the reminder x times
for ($i = 0; $i <= $repeatAmount; ++$i) {
echo $date->format('d/m/Y');
$date->modify('+'. $interval .' day');
}
$date = new DateTime()Imagine this is the date the user entered, this is our starting point, our first reminder will at this time.
$interval and $repeatAmount are the interval in days, i.e. I want this to every 2 days and the amount of times you want it to repeat, in our example 2.
for ($i = 0; $i <= $repeatAmount; ++$i) { We want to loop as many times as the user says they want to repeat. Little note ++$i tends to be a very minor performance boost over $i++ in some scenarios, so it is usually better to default to that unless you specifically need to use $i++
echo $date->format('d/m/Y'); Simply print out the date, i'll let you handle the reminder logic.
$date->modify('+' . $interval . ' day'); Increment the dateTime object by the interval that the user has asked for, in our case increment by 2 days.
Any questions let me know.
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've got to write a loop that should start and end between two times. I know there are many ways to skin this cat, but I'd like to see a real programmers approach to this function.
Essentially I have Wednesday, for instance, that opens at 6:00pm and closes at 10:30pm.
I'm looking to write a loop that will give me a table with all of the times in between those two in 15 minute intervals.
So, I basically want to build a one column table where each row is
6:00pm
6:15pm
7:15pm
etc...
My two variables to feed this function will be the open time and the close time.
Now don't accuse me of "write my code for me" posting. I'll happily give you my hacked solution on request, I'd just like to see how someone with real experience would create this function.
Thanks :)
$start = new DateTime("2011-08-18 18:00:00");
$end = new DateTime("2011-08-18 22:30:00");
$current = clone $start;
while ($current <= $end) {
echo $current->format("g:ia"), "\n";
$current->modify("+15 minutes");
}
Try it on Codepad: http://codepad.org/JwBDOQQE
PHP 5.3 introduced a class precisely for this purpose, DatePeriod.
$start = new DateTime("6:00pm");
$end = new DateTime("10:30pm");
$interval = new DateInterval('PT15M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $time) {
echo $time->format('g:ia'), PHP_EOL;
}
echo $end->format('g:ia'); // end time is not part of the period
$start = strtotime('2011-08-11 18:00:00');
for ($i = 0; $i < 20; $i++) {
echo date('g:ia', $start + ($i * (15 * 60))), '<br>';
}
I would go with the DateTime functions and increase the time by 15 minutes every loop-turn as long as the current time is lower then the end-time.
EDIT: as user576875 has posted
$start_date = '2019-07-30 08:00:00';
$end_date = '2019-09-31 08:00:00';
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_date<br>";
$start_date = date ("Y-m-d H:i:s", strtotime("+1 hours", strtotime($start_date)));
}