I have a list of unix timestamps in a database, and I wanting to select the ones that are from today.
i.e If today is Tueday, I want to get all the timestamps that were made today? Is it possible? Is there such a things as strtotime("Today")?
Any help would be great
you can use mktime() to generate the timestamp for the start of the day and then find the database entries with a timestamp greater than that.
$start = strtotime(date('Y-m-d 00:00:00')); // Current date, at midnight
$end = strtotime(date('Y-m-d 23:59:59')); // Current date, at 11:59:59 PM
then, you can just select where the timestamp is between the above 2 timestamps:
"SELECT FROM `foo` WHERE `timestamp` BETWEEN '{$start}' and '{$end}'"
You can convert the unix timestamps to sql dates in the SQL using FROM_UNIXTIME(), then compare those to NOW()
SELECT * FROM `tablename` WHERE DATE(FROM_UNIXTIME(`dateFld`)) = DATE(NOW());
Check if DAY(NOW()) and MONTH(NOW()) and YEAR(NOW()) is equal to appropriate value of DAY(timestamp) and MONTH(timestamp) and YEAR(timestamp).
select timestamp from table where DAY(NOW()) = DAY(timestamp) AND MONTH(NOW()) = MONTH(timestamp) AND YEAR(NOW()) = YEAR(timestamp)
If you're using mysql:
SELECT * FROM table WHERE DATE(NOW()) = DATE(FROM_UNIXTIME(timestampcol))
FROM_UNIXTIME(somefield) can be compared to CURDATE() assuming you're using MySQL
SELECT * FROM mytable WHERE FROM_UNIXTIME(datefield,'%Y-%m-%d') = CURDATE();
ETA:
Okay, I was assailed by doubt when this answer was marked down. So I went and did a couple of tests. Given MySQL it definitely works. So why the downmod?
Consider this test which outputs 2 identical fields for every row in a table:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(CURDATE()),'%Y-%m-%d') a , CURDATE() b
FROM tablewithsomerows
WHERE FROM_UNIXTIME(UNIX_TIMESTAMP(CURDATE()),'%Y-%m-%d') = CURDATE();
Related
I am trying to get the sum of the sales for the last week / month with php and mysql pdo. The sales date saved in unix timestamp format in database.
This is how I'm doing it right now;
$week = strtotime("+1 Week");
$getsales = $odb -> prepare("SELECT SUM(`amount`) FROM `sales` WHERE `date` < :date");
$getsales -> execute(array(':date' => $week));
Can someone give me a better way for it ?
You can use UNIX_TIMESTAMP function to convert date into timestamp and use it in the query, e.g.:
SELECT SUM(`amount`)
FROM `sales`
WHERE `date` BETWEEN UNIX_TIMESTAMP(DATE_ADD(NOW() -7 DAYS)) AND UNIX_TIMESTAMP(NOW());
Here's the documentation for UNIX_TIMESTAMP.
I want to get count of previous day records from database.
I am using following method
$date = date('Y-m-d H:i:s', strtotime('-1 day'));
$users = 'SELECT Count(*) FROM users where date="'.$date.'"';
This is show count 0 as date format in database is (Y-m-d H:i:s).
Thanks.
Could just do
select count(*) from users where to_days(date) = (to_days(now()) - 1);
This is useful if your date column is a datetime - we're just converting to a day number and checking how many records have yesterdays day number.
Hope it will help you
SELECT COUNT(*) FROM users WHERE date = (CURDATE() - INTERVAL 1 DAY)
You might want to consider asking MYSQL itself about it, so that PHP doesn't have to compute it (and it is likely to be faster) :
SELECT Count(*) FROM users WHERE date = DATE_SUB(NOW(), INTERVAL 1 DAY)
Here is a query to get all rows in the past month.
$time = time() - 9676800;
$q = $this->db->query("
select id
from ipAddress
where date > {$time}
");
But how can i adjust this query to get all rows BESIDES the past month? Basically I want to end up deleting all rows over 1 month old
So long as your methodology for calculating "last/past month" satisfies you, then it's simple:
where date <= {$time}
You can use date_format, date_sub functions to get last month's dates.
Find answers here:
mysql last month date statement
and here
MySQL Query to calculate the Previous Month
You can do it like so
$time = strtotime('-1 Month');
$q = $this->db->query("
select id
from ipAddress
where `date` <= {$time}
");
but if date is a TIMESTAMP, DATE, or DATETIME string like 2013-02-27 22:16:38 or 2013-02-27 then you need something like
$time = date('Y-m-d H:i:s', strtotime('-1 Month'));
$q = $this->db->query("
select id
from ipAddress
where `date` <= '{$time}'
");
Or purely in SQL
select id
from ipAddress
where `date` <= DATE_SUB(NOW(), INTERVAL 1 MONTH)
And if I remember correctly, date is a reserved mysql word so use backticks in your sql.
How can i get one day old record from database from server . i have use datetime to insert record. below is how record is look like.
2013-01-15 23:44:02
i have use strtotime('-1 day') but it returns local system time.i want to get one day old record and do some stuff in condition..
Thanx in advance..
where date(date_column) = DATE_sub(NOW(), INTERVAL 1 DAY);
use DATE_ADD
SELECT *
FROM tablename
WHERE DATE(dateCol) = DATE_ADD(CURDATE(),INTERVAL -1 DAY)
DATE_ADD()
SELECT * from table WHERE datefield < DATE_SUB(NOW(), INTERVAL 1 DAY)
You will be archiving this with sql query.
SELECT * FROM tablename WHERE DATE(datefield)=DATE_ADD(CURDATE(),INTERVAL 1 DAY)
CURDATE() will return the current Mysql Server time.
You can use this function DATE_SUB(date,INTERVAL expr type)
http://www.w3schools.com/sql/func_date_sub.asp
Example provided in W3schools
Assume we have the following "Orders" table:
Columns: OrderId, ProductName, OrderDate
Values: 1, Jarlsberg Cheese, 2008-11-11 13:23:44.657
Now we want to subtract 5 days from the "OrderDate" date.
We use the following SELECT statement:
SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 5 DAY) AS SubtractDate
FROM Orders
$yesterday = strtotime('Y-m-d h:i:s','yesterday');
SELECT * FROM tablename WHERE datefield = '$yesterday'
I have the following relation in my schema:
Entries:
entryId(PK) auto_inc
date date
In order to count the total entries in the relation I use a query in my php like this:
$sql = mysql_query("SELECT COUNT(*) as Frequency FROM Entries WHERE date = '$date'");
My question is how can I count the number of entries for the CURRENT month..
You want a between query based on your date column.
WHERE date BETWEEN startdate AND enddate.
Between is equivalent to date >= startdate AND date <= enddate. It would of course be also possible to just use >= AND < explicitly which would simplify it a bit because you don't need to find the last day of the month, but just the first day of the following month using only DATE_ADD(..., INTERVAL 1 MONTH).
However startdate and enddate in this case would be derived from CURDATE().
You can use CURDATE(), MONTH(), DATE_ADD and STR_TO_DATE to derive the dates you need (1st day of current month, last day of current month). This article solves a similar problem and all the techniques needed are shown in examples that you should be able to adapt:
http://www.gizmola.com/blog/archives/107-Calculate-a-persons-age-in-a-MySQL-query.html
The first day of the current month is obvious YEAR-MONTH(CURDATE())-01. The last day you can calculate by using DATE_ADD to add 1 Month to the first day of the current month, then DATE_ADD -1 Days.
update-
Ok, I went and formulated the full query. Don't think str_to_date is really needed to get the index efficiency but didn't actually check.
SELECT count(*)
FROM entries
WHERE `date` BETWEEN
CONCAT(YEAR(CURDATE()), '-', MONTH(CURDATE()), '-', '01')
AND
DATE_ADD(DATE_ADD(CONCAT(YEAR(CURDATE()), '-', MONTH(CURDATE()), '-', '01'), INTERVAL 1 MONTH), INTERVAL -1 DAY);
Try this
SELECT COUNT(1) AS `Frequency`
FROM `Entries`
WHERE EXTRACT(YEAR_MONTH FROM `date`) = EXTRACT(YEAR_MONTH FROM CURDATE())
See EXTRACT() and CURDATE()
Edit: Changed NOW() to CURDATE() as it is more appropriate here
Try
$sql = mysql_query("SELECT COUNT(*) as Frequency FROM Entries WHERE MONTH(date) = MONTH(NOW()) );