Logic about dates in PHP - php

I'm creating a report in php in which 6 html drop downs appear and prompt the user to enter the two dates in which they would like to see the data of the report. So for example the report goes as follows:
See data between: [month][day][year] and [month][day][year] (where the brackets signify a select tag)
Also in this report is a function which calculates the percentage increase or decrease from the previous day. So for example if the user does not select any date range, it's simply data of the current day and the percentage is calculated as:
round(((($newDataPointCount - $yesterdayDataPointCount) / $yesterdayDataPointCount) * 100),2)
This is obviously very easy to calculate for only one day because I can tell it to query the SQL database with INTERVAL 1 DAY. But here is my question, how would I calculate the number of day intervals if the months change?
Everything would work great if the user stays within one month so it would be something like [March][20][2012] - [March][29][2012], and I can easily calculate the value is 9, but when it's something like [February][27][2012] - [March][20][2012], how can I calculate the number of days in between?
Just to clarify any questions that may arise, I'm using PHP and MySQL and would prefer to stay within those bounds.

The MySQL DATEDIFF function should accomplish the task
DATEDIFF

Dates are not scalars and should not be treated as such. My advice is to user the proper tools for date arithmetic.
A lot of people suggest unix timestamp oriented date math:
$a = '2012-02-12 14:03:50';
$b = '2012-05-30 00:55:03';
$days = (strtotime($b) - strtotime($a))/86400;
However, daylight saving time and all of kinds of factors can make that type of math wrong.
My approach is to typically use DateTime:
$a = new DateTime('2012-02-12 14:03:50');
$b = new DateTime('2012-05-30 00:55:03');
$diff = $b->diff($a);
//$diff is now a DateInterval
However, to answer your real question, I would not pull the data from MySQL based on MySQL date math, but rather I would just give it dates.
WHERE d >= '2012-02-27' AND d <= '2012-03-29';
Though based on your requirements, you may need to alter the 27 to 26 as to grab the previous day and do the calculations with it.
As for doing the changes in point values, I would either precalculate and store them, or I would just calculate them in PHP. There's no simple way to tell SQL "hey grab every record between these dates and while you're at it, do some math with each record's previous record."
I hope this has been clear, but I have a feeling it borders on rambling other than clarity, so if so, please let me know and I'll edit my answer.

Related

How to auto empty table on specified time

I need to remove all records in my table when time is 23.59, I have the following query:
function delChat() {
$date = date('H:i');
$this->db->where(dimasukkan, '23:59');
$this->db->delete('chat');
}
but nothing happens
Please be aware that I don't know PHP, so I can't provide working code. However, I'll try to help out.
First, your question is ambiguous. Do you mean that you want to remove all records from the table every day when it is 23:59 h, or do you mean that you must remove every record whose timestamp is 23:59 h?
If you want to empty the table every day when it is 23:59 h, a cron job would be the right thing (as some comments already propose).
The cron job could be used on Linux / Unix systems; an alternative to that would be at. Under Windows, you could use the task scheduler for regularly running your job.
In every case, please be aware that you actually can't predict how long the operation will take. Possibly it will still run when it is already 00:00 h, or even 00:01 h the next day, which will eventually get you into trouble.
If you want to delete every row whose timestamp or date column is 23:59 h, your code has some problems:
Your where statement is wrong. You are comparing a normal variable to a constant here. I have no clue what PHP / MySQL are doing in such cases, but it certainly is not what you expect. If you want to compare e.g. a date column to that constant, you would have to it that way: ... where('date', '23:59').
Almost certainly, your date column or timestamp does not contain the date / time in the format needed. Hence, if you want to compare hour:minute to your date or timestamp column, you would first have to extract the hour and the minute from it and concatenate that to the format needed (or perhaps MySQL already provides an appropriate function for that), and then compare the result to your string constant.

How to make the final value of a countdown become new starting value?

I am working on a school project where I am keeping track of a user's tweeting frequency per week. I have working code, but at the end of each 1-week period, I need to manually adjust the new starting tweet total and the date of one week in the future.
How can I automate it so the final tweet count becomes the new starting tweet count, and one week gets added to the ending date? Am I heading in the right direction with the code below, or should I be storing these final tweet total values in a database? Thank you!
// Get current tweet total and calculate current count
$ptTotal = $ptObject->{'statuses_count'};
$ptStart = 572;
$ptCount = ($ptTotal-$ptStart);
// Set end date & convert to EST
$ptdatestr="2017-05-30 12:00:00";
$ptdate=strtotime($ptdatestr)+14400;
// Calculate time remaining
$ptdiff=$ptdate-time();
$ptdays=floor($ptdiff/86400);
$pthours=round(($ptdiff-$ptdays*86400)/3600);
// Re-set start value and add one week to countdown
if ($ptdiff <= 0) {
$ptStart = $ptTotal;
$ptdate = $ptDate + 604800;
}
I say regardless of how you are automating this code block (see Alejandro's comment), you should move away from using any approach that includes +86400 (or a factor of). Things will go BONK in the night when daylight savings is involved.
Instead, I recommend that you integrate DateTime objects. They are highly versatile and have specific features that will aid you in your specific project. This is a full list of related functions: http://php.net/manual/en/book.datetime.php
Implementing Datetime objects and functions will make your project solid and lean. Immerse yourself in the above php manual pages and the comments that follow; and continue to research on StackOverflow.
More to your specific questions: Yes, I think you are on the right path. Yes, I think I'd store the data in a database.
Good luck.

Can month and day values in a PHP and MYSQL DATE variable be 0 or null?

I'm in the planning stages of creating a historical database. I will be using PHP, MYSQL and JavaScript for the website.
Often someone will know what year a person was born or picture was taken, but not the month or the day.
Is it possible for a PHP DATE variable and MYSQL DATE to be:
1920-00-00 or 1845-12-00 ?
If not, unless someone has a better idea, I'll have to create a column for year, another column for month, and yet another for day then do a bunch of value checking and combining.
Thoughts?
Thanks.
You need exakt dates for using date in mysql, so you probably have to bite down and filter everything for validating and then some code to combine it.

Inserting actual hours (not time) to MySQL

I am trying to insert actual hours not the time itself to MySQL database through form fields. So for example
$time1 = '00:00';
$time2 = '27:20';
$time3 = '00:45';
So I can retrieve the different rows and can calculate on the fly whenever require. Either through search query or even in other area of the system.
When I have tried to do addition of above three times, it is not giving the result the way I am looking for
$total = strtotime($time1) + strtotime($time2) + strtotime($time3);
echo date('H:i:s', $total);
The result
14:16:44
While it should be something like
28:05:00
I have used TIME DATATYPE in MySQL table. I may use as a TEXT but I am also concern about the error happen in user input. Where I do not have to force the user to insert the any particular format but they can either insert as below way
27.20
27:20
or
1.5
1:30
My main concern is to calculate the time, the user input can be on second priority but it would be great if can implement.
So is there anyway, idea or hint to achieve this?
date() expects the timestamp in UNIX format, i.e. seconds since January 1 1970 00:00:00 UTC (which is also the value provided by strtotime)
You're passing it the result of adding a series of amounts of time since 1 January 1970 instead of just adding up hours, so (as far as date is concerned) you're generating a random date and time, and printing only the time (try printing the date of $total and see what you get).
Since your time is stored in the database, one possibility is to let MySQL handle the time calculations itself, e.g.:
SELECT ADDTIME('00:00',ADDTIME('27:20','00:45'))
will result in "28:05:00". You can have your database fields as TIME and operate on them directly through SQL, and do the user input conversions into acceptable TIME values in PHP.
If you're only interested in the hours and minutes, why don't you just store the value as an in integer? Just multiply the hours by 60.
You can handle the conversion in PHP.
Alternatively, you can also easily use two (very small) int fields for this.

PHP and MySQL - display contnet of column between certain numerical values

I'm new to MySQL and PHP but was wondering if someone could help me with a little project I'm doing for my boss.
I have a SQL database (MyDB) and a table in there (mytable) with two columns - the first column (index) is an auto-incrementing integer from 1-10, the second column (date) has different dates and timestamps in the format of Year-month-day time 2013-04-12 1326
I'm trying to create a simple PHP page that first gets the current date (easy enough) then looks at the table and shows the number of rows that fall within yesterday's date. For example, if I have 3 rows with 2013-04-11 XXXX and 2 rows with 2013-04-12 XXXX (and today is the 12th April 2013) the page will display 3. (The time is not important but we can't remove it from the table as it's auto created by one of the other staff's programs and he refuses to change it).
So far I've got my php page, done a connection to the DB and defined two variables:
$startdate = date('Y'."-".'n'."-".'d'." "."0000");
$enddate = date('Y'."-".'n'."-".'d'." "."2359");
As the timestamp doesn't matter I've gone for the min/max possible on the variables. I realise this will only give the current date, trying to work out how to get it to display the previous day as the date in the variable.
Now I'm trying to create a sql query that will count the number of rows where the date field falls within the startdate and enddate variables (-1 day) but not too sure where to start or how this would look. I then need to output this as a variable in PHP so I can echo it later in the page.
Anyone able to point me in the right direction? Hope any of this makes sense.
You could write a query with no params to do this (if its always just yesterday).
SELECT * FROM <table>
WHERE DATE_FORMAT(<date column>,'%j-%Y') = DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 DAY), '%j-%Y');
Date functions in the where clause might not be super awesome performance wise

Categories