timestamp query not retrieving results? - php

Hi there :) I am doing a query, and it will pull results where the timestamp is more than 30 days old. Here's what I've put so far:
$result = $db->query("SELECT time FROM table1 WHERE open_time < (NOW() - INTERVAL 30 DAYS)");
So as you can see, it will try to find results more than 30 days old, however when I execute the query, it doesn't select any rows, even though the column field "open_time" is more than 30 days old.
Any suggestions I do greatly appreciate :)

Have you tried to cast the date field?
$result = $db->query("SELECT time FROM table1 WHERE CAST(open_time AS DATE) < (NOW() - INTERVAL 30 DAYS)");
EDIT:
Maybe you should use this tricky query:
$result = $db->query("SELECT time FROM table1 WHERE open_time <
UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))"):

Try this Query
$result = $db->query("SELECT time FROM table1 WHERE DATE(`date`) = DATE(NOW() - INTERVAL 30
DAY")
or
try this one also for your reference
timestampadd()
SELECT * FROM table WHERE `date` > timestampadd(day, -30, now());
try this link also

Related

Unable to filter SQL data from last 30 days

I want to collect data from SQL from the last 30 days.
This code shows data of all time
$result = $dbh->query('SELECT country,COUNT(*) FROM data_able GROUP BY country');
this shows nothing, instead of showing last 30 days data.
$result = $dbh->query('SELECT country,COUNT(*) FROM data_able GROUP BY country WHERE dtime > DATE_SUB(CURDATE(), INTERVAL 30 DAY)');
All SQL entries were made within the last 30 days.
also tried
$result = $dbh->query('SELECT country,COUNT(*) FROM data_able WHERE dtime > DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY country');
What am I doing wrong here ?
Try this:
SELECT country, COUNT(*)
FROM data_able
WHERE dtime > DATE_ADD(CURDATE(), INTERVAL -30 DAY)
GROUP BY country
The second doesn't work because you put GROUP BY before WHERE statement, which is not correct SQL order.
As for why the third code doesn't work, I'm not sure, but if I had to guess, it has something to do with that DATE_SUB statement.

Not showing what it need to shows

Im trying to make a count of the lasts IDs created in the day and the lasts in the month using this code
$TodayAttacks = $odb->query("SELECT COUNT(id) FROM `logs`
WHERE `date` BETWEEN DATE_SUB(CURDATE(), INTERVAL '-1' DAY) AND
UNIX_TIMESTAMP()")->fetchColumn(0);
$MonthAttack = $odb->query("SELECT COUNT(id) FROM `logs`
WHERE `date` BETWEEN DATE_SUB(CURDATE(), INTERVAL '-30' DAY) AND
UNIX_TIMESTAMP()")->fetchColumn(0);
I put it on the html like always but later foto
It shows 0 and thats incorrect. The things that work good is to show the total and running ids.
$RunningAttacks = $odb->query("SELECT COUNT(*) FROM `logs` WHERE `time` + `date` > UNIX_TIMESTAMP() AND `stopped` = 0")->fetchColumn(0);
$TotalAttacks = $odb->query("SELECT COUNT(*) FROM `logs`")->fetchColumn(0);
Both of this things work but the other ones to calculate in a day and in a month dont works, just it shows 0.
Here is how the IDs on the MySQL works
foto
I need help to fix the $TodayAttacks and $MonthAttack to calculate what they need to.
If someone knows how to fix this tell me :)
Since you're using the DATE_SUB function you won't need negative numbers for your interval value. To get the running count from yesterday until now:
$TodayAttacks = $odb->query("SELECT COUNT(id) FROM `logs`
WHERE `date` > UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 1 DAY))")->fetchColumn(0);
To get the count for the last 30 days, try:
$MonthAttack = $odb->query("SELECT COUNT(id) FROM `logs`
WHERE `date` > UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 30 DAY))")->fetchColumn(0);
An example of how this works is posted here:
https://www.db-fiddle.com/f/itLtCzJbPbWuCWcx3jLiMk/1

Calculate the difference b/w two months data

I have a mysql table orders in that I have a column order_date which is current time stamp(2016-08-17 00:00:00.000000). now I want to select or count the data's entered this month and the previous month, after this I can find the difference between these two months I am using this code and it is not working.
$sql="SELECT * FROM order WHERE order_date > DATE_SUB(NOW(), INTERVAL 1 MONTH)";
$result = $this->db->query($sql);
return $result;
this is not working an mysql error is produced.
Try
$sql="SELECT * FROM order WHERE DATE(order_date) LIKE DATE_SUB(CURDATE(), INTERVAL 1 MONTH)";
$result = $this->db->query($sql);
return $result;
i think this Link[http://sqlhints.com/2015/07/10/how-to-get-difference-between-two-dates-in-years-months-and-days-in-sql-server/] will help you
Use this. Hope it helps what you want. Thanks
$todayDate = date('Y-m-d');
$todayMonth = date("m", strtotime($todayDate ));
$previousMonth = $todayMonth - 1;
$sql = "SELECT * FROM order WHERE MONTH(order_date) BETWEEN '$todayMonth' AND '$previousMonth'";
First, the following is the correct logic to get all values from the current month and all of the previous month:
select *
from orders o
where order_date >= date_sub(date_sub(curdate(), interval day(curdate) - 1 day), interval 1 month);
Then, use conditional aggregation for comparison. Here is an easy way:
select sum(month(order_date) = month(curdate())) as cur_month,
sum(month(order_date) <> month(curdate())) as prev_month,
(sum(month(order_date) = month(curdate())) -
sum(month(order_date) <> month(curdate()))
) as diff
from orders o
where order_date >= date_sub(date_sub(curdate(), interval day(curdate) - 1 day), interval 1 month);
Note: I don't fully see the utility of comparing a partial month (this month) to a full month (last month), but that is what you seem to be asking for. If you are asking for something different, then ask another question with sample data and desired results.

select from table where day difference is less than some number

I am trying to grab all SQL entries WHERE Day difference between current date and expiration date is < than 4 days
My first approach was following:
$sql_i_requested = "SELECT *, (To_days(date_return)-TO_DAYS(NOW())) as daydif FROM ".$tbl_name."
WHERE (status!='completed' AND status!='canceled')
AND owner_id=".$owner_id."
AND daydif < 4
ORDER BY date_created DESC";
My second aproach is (according to SQL DateDifference in a where clause):
$sql_i_requested = "SELECT * FROM ".$tbl_name."
WHERE (status!='completed' AND status!='canceled')
AND owner_id=".$owner_id."
AND date_return > DateAdd(day, -3, getdate())
ORDER BY date_created DESC";
Neither of them work, so how do I select FROM table WHERE day_difference between "date_return" and now() is less than 4 days?
EDIT:
changed
AND daydif < 4
to
AND (To_days(date_return)-TO_DAYS(NOW())) < 4
and now it's working. Anyway, maybe you guys could suggest other solutions.
Using the DATEDIFF
WHERE DATEDIFF(date_return, now()) < 4
try:
SELECT DATEDIFF(date_return, NOW()) AS dayDiff;
and
having dayDiff < 4
Try this:
select *
from table
where DATEDIFF(day, present, future) < 4

SQL Query to show number of stories created in last 24 hours?

I'm trying to create a custom query that will show the number of stories that have been posted in the last 24 hours on a Drupal 6 site.
Stories are stored in the "node" table. each record has a "created" row that records the UNIX timestamp when the story was posted.
Here's the query I'm trying so far:
$sq = 'SELECT COUNT(*) cnt '
. 'FROM {node} c WHERE created >= dateadd(hour,-24,getdate())';
This doesn't appear to be working though. What am I doing wrong?
EDIT: Here's the overall code I'm trying to use right now:
$sq = 'SELECT COUNT(*) AS cnt FROM {NODE} n WHERE FROM_UNIXTIME(n.created) >= DATE_SUB(NOW(), INTERVAL 1 DAY)';
$q = db_query($sq);
while ($o = db_fetch_object($q)) {
print_r($o);
}
That print_r isn't returning anything. Where's my error?
For MySQL, use:
SELECT COUNT(*) AS cnt
FROM NODE n
WHERE FROM_UNIXTIME(n.created) >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Mind that NOW() includes the time when the statement is run. If you want to count records, starting from midnight of the previous day, use:
SELECT COUNT(*) AS cnt
FROM NODE n
WHERE FROM_UNIXTIME(n.created) >= DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY)
Reference:
FROM_UNIXTIME
DATE_SUB
Since you are doing this in PHP, you can just use $_SERVER['REQUEST_TIME']. My guess is that it will be faster than doing date manipulations with SQL:
$count = db_result(db_query("SELECT COUNT(nid) FROM {node}
WHERE created >= %d;", $_SERVER['REQUEST_TIME'] - 86400));
Alternative you could use time to get the current timestamp, but that will be a tiny bit slower than using the $_SERVER['REQUEST_TIME'] variable.

Categories