Retrieve only today records from MySQL database using PHP - php

In my database I stored date and time as a TIMESTAMP values. I want to retrive only today data from the database. This is code that I tried
$today = date("Y-m-d") . '00:00:00';
$last = date("Y-m-d") . '23:59:59';
$sql = "SELECT id, name, name2,some,some,submittimestamp,some FROM recs where submittimestamp Between $today AND $last";
$result = $conn->query($sql);
But I only get the 0 results message using this. There is more than 100 rows added today.
How can I solve this ? I cant change the database now. only way to solve this is change the PHP script
Do I need to convert PHP datetime to MYSQL timestamp ?
This is my sample database entry time-stamp value
2014-10-02 15:47:01
I only want to retrieve data for one day. time is not required !!

SELECT id, name, name2, submittimestamp
FROM recs WHERE submittimestamp > DATE_SUB(CURDATE(), INTERVAL 1 DAY);
Also you may try this, as DATE() ignores time part
SELECT id, name, name2, submittimestamp
FROM recs WHERE DATE(submittimestamp) = CURDATE();

Related

Adding days to a Date (retrieved from MySQL database) in PHP

I am trying to do, what I assume is, an easy task of adding days to a date.
I have a date stored in a MySQL table, in a column called meta_date, with the type of DATE (A date, supported range is 1000-01-01 to 9999-12-31)
I retrieve this date from the database as follows:
$thisId = 1;
$dateQuery = mysqli_query($connection, "SELECT * FROM `sometable` WHERE `id` = '$thisId'");
$fetchDate = mysqli_fetch_assoc($dateQuery);
$theDate = $fetchDate['meta_date'];
Now I add a number of days to this date.
$newDate = date("Y-m-d", strtotime($theDate . " + 7 days"));
Next I put it back inside the database with an UPDATE query.
$editDate = mysqli_query($connection, "UPDATE `sometable` SET `meta_date` = '$newDate' WHERE `id` = '$thisId'");
However the date always returns as 0000-00-00 after the update.
Am I missing something here to do with the way the date is handled in PHP?
edit: The data I first retrieve from the database (into $theDate) is "2016-11-30".
You can use Mysql's built in function DATE_ADD()
Syntext
DATE_ADD(date,INTERVAL expr type) Where date is a valid date expression and expr is the number of interval you want to add.
For your case
UPDATE sometable
SET `meta_date` = DATE_ADD(`meta_date` , INTERVAL 7 DAY)
WHERE `id` = '$thisId';

Select between dates from table - strtotime?

I have been trying for a while, read countless stackoverflow answers and still cant crack it!
I have a table in my db with a field called dob. This field is currently just a TEXT field (but i have since tried changing it to a DATE field and still cant get it to work).
The DOB field's data is in this format (UK dates) - 22/05/2016.
Im trying to find out the number of users who's birthdays are between two dates.
For example, anyone who was born in the last two years:
$twoyearsago=date('d/m/Y', strtotime("-2 years"));
$today = date("d/m/Y");
$sql = mysql_query("SELECT * FROM users WHERE dob >= '" . $twoyearsago . "' AND date <= '" . $today . "' ORDER by id DESC");
I also tried:
$sql = mysql_query("SELECT * FROM users WHERE dob BETWEEN '" . date('d-m-Y', strtotime($twoyearsago)) . "' AND '" . date('d-m-Y', strtotime($today)) . "'";
Hopefully you can see where me logic is and hoping you will see where im going wrong - any help would be appreciated.
Jack
With STR_TO_DATE can you convert your date
NOTE: i have changed the Column type from TIMESTAMP to DATE, because in a TIMESTAMP you can store date before 1970-01-01.
SELECT STR_TO_DATE('22/05/2016','%d/%m/%Y');
sample
MariaDB [bb]> SELECT STR_TO_DATE('22/05/2016','%d/%m/%Y');
+--------------------------------------+
| STR_TO_DATE('22/05/2016','%d/%m/%Y') |
+--------------------------------------+
| 2016-05-22 |
+--------------------------------------+
1 row in set (0.00 sec)
MariaDB [bb]>
so you can change you Table
ALTER TABLE `users`
ADD COLUMN new_dob DATE;
UPDATE `users` SET new_dob = str_to_date(dob,'%d/%m/%Y');
** Verify the dates
ALTER TABLE `users`
DROP COLUMN dob;
ALTER TABLE `users`
CHANGE COLUMN `new_dob` `dob` DATE;
** CREATE an INDEX for perfomance **
ALTER TABLE `users`
ADD KEY (`dob`);
SELECT
SELECT * from `users` where dob between '2014-01-01' AND `2015-08-01';
The problem with many local date formats is that their lexical and chronological order are different (eg, 16-11-2016 comes after 11-12-2016 lexically, but before chronologically). That's why storing dates in string fields in some regional format is in most cases a bad idea: you will get sorting issues sooner or later.
Next, when specifying dates literally for MySQL, you have to respect certain formats, as explained in the documentation
Putting that into practice, the range variables should look something like this:
$today = date("Y-m-d");
$twoyearsago=date("Y-m-d", strtotime("-2 years"));
Then we use a built-in function str_to_date to convert the string column into a date that can be compared correctly:
SELECT * FROM users WHERE
STR_TO_DATE(dob, '%d/%m/%Y') between '$twoyearsago' and '$today'
This will work, but in the long run you're much better off converting that dob column into a real date format (as #BerndBuffen shows) as it's clearer, easier to internationalize and a lot better performing.
Sidenote: you are still using the long-deprecated mysql_ extension. You should really switch to either mysqli_ or PDO.
You need to build your query by using actual date values, not string. So you need format YYYY-MM-DD in query - both side of the comparison.
Try following.
$twoyearsago=date('Y-m-d', strtotime("-2 years"));
$today = date("Y-m-d");
$sql = mysql_query("SELECT * FROM users WHERE STR_TO_DATE(dob, '%d/%m/%Y') >= '" . $twoyearsago . "' AND STR_TO_DATE(dob, '%d/%m/%Y') <= '" . $today . "' ORDER by id DESC");
STR_TO_DATE(dob, '%d/%m/%Y') makes sure your d/m/Y saved dob string value to be converted to date in the query that MySQL can understand and compare with the given YYYY-MM-DD values.
Actually the proper way is creating a date field and transferring dob string values as date to this new field by using the same function unless you will always get the date values as string into the dob field.
Another method is to use DateTime and format the date before doing your query.
$begin = '10/02/2014';
$emd = '10/02/2015';
$beginDate = DateTime::createFromFormat('d/m/Y', $begin);
$emdDate = DateTime::createFromFormat('d/m/Y', $emd);
$stmt = "
SELECT
...
FROM users
WHERE birthday >= '".$beginDate->format('Y-m-d')."'
AND birthday <= '".$endDate->format('Y-m-d')."'
";

MySQL & PHP: summing up data from a table

Okay guys, this probably has an easy answer but has been stumping me for a few hours now.
I am using PHP/HTML to generate a table from a MySQL Table. In the MySQL table (TimeRecords) I have a StartTime and EndTime column. In my SELECT statement I am subtracting the EndTime from the StartTime and aliasing that as TotalHours. Here is my query thus far:
$query = "SELECT *,((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date
BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
ORDER BY Date
";
I then loop that through an HTML table. So far so good. What I would like to do is to add up all of the TotalHours and put that into a separate DIV. Any ideas on 1) how to write the select statement and 2) where to call that code from the PHP/HTML?
Thanks in advance!
Try this
$query= "
SELECT ((EndTime - StartTime)/3600) AS Hours, otherFields, ...
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31' ";
$records =mysql_query($query);
$sum= 0;
while($row=mysql_fetch_array($records))
{
echo"$row['otherFields']";
echo"$row['Hours']";
$sum+=$row['Hours'];
}
echo" Total Hours : $sum ";
Just use a single query with a Sum(). You could also manually calculate it if you're already displaying all rows. (If paginating or using LIMIT, you'll need a separate query like below.)
$query = "
SELECT Sum(((EndTime - StartTime)/3600)) AS SumTotalPeriodHours
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31'
";
You can do this in the same query if you have a unique id using GROUP BY WITH ROLLUP
$query = "
SELECT unique_id,SUM((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
GROUP BY unique_id WITH ROLLUP
ORDER BY Date
";
In this instance the last result from your query with contain NULL and the overall total. If you don't have a unique ID you will need to do it in PHP as per Naveen's answer.
A few comments on your code:
Using SELECT * is not considered good practice. SELECT the columns you need.
Not all months have a day 31 so this may produce unexpected results. If you're using PHP5.3+, you can use
$date = new DateTime();
$endDate = $date->format( 'Y-m-t' );
The "t" flag here gets the last day of that month. See PHP docs for more on DateTime.

SQL Items within the Last Day

In my code, I am trying to find items in an activities table that are within the last day. This query is not returning any results, are there any problems with it? Is there a better query?
$curday = time() - (24*3600);
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > '$curday'";
There are two choices here, you can get and format the date through PHP or use SQL language to do it. I prefer to do it within the SQL, it also allows me to use the same query in a MySQL client.
This question is essentially the same thing: MySQL SELECT last few days?
This would be the new query:
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > DATE_ADD(CURDATE(), INTERVAL -1 DAY)";
you can try with unix function 'mktime' to get value of yesterday ..
as
$curday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
for reference
if your database will mysql only then you can extract yesterday in sql itself..
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY)
one more thing if timestamp is your column name don't put this column inside single quote ..
What you can use is DATE_SUB. This can be used as follows
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > date_sub(current_date, interval 1 day)
This way you don't need to work with current date in PHP
in Informix it would be (TODAY - 1) if the column is type DATE

Mysql query: retrieve current date query

In mysql database i have this column called:
Name: Date
Type: datetime
I have few values in that column:
2009-01-05 01:23:35
2009-03-08 11:58:11
2009-07-06 10:09:03
How do I retrieve current date? I am using php.
in php:
<?php $today = date('Y-m-d');?>
How to write a mysql query to retrieve all today date data?
Should i change the column type to "date", then insert values like "2009-07-06" only, no time values???
You don't need to use PHP, MySQL has a function to get the current date:
SELECT field FROM table WHERE DATE(column) = CURDATE()
Documentation: CURDATE, DATE.
If your column is only ever going to need the date part and never the time, you should change your column type to DATE. If you insist on doing it through PHP, it is the same thing, really:
$today = date('Y-m-d');
$query = mysql_query("
SELECT field FROM table WHERE DATE(column) = '$today'
");
For date time it is not usefull, instead I try this and working...
Today's Visitors!
sql > select user_id from users where last_visit like concat('%' , CURDATE() , '%');
// last_visit coloumn of type 'datetime'

Categories