Select from database where date is less than a supplied date - php

I'm trying to pull rows from a database where the date is within two weeks of the current date, I'm using CodeIgniter and this is my model:
function GetToDoItems($userID)
{
$range = date('Y-m-d', strtotime("+2 weeks"));
$query = $this->db->query("SELECT * FROM FYP_Milestones
INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID
WHERE FYP_Milestones.MilestoneDue < $range
ORDER BY FYP_Milestones.MilestoneDue ASC
");
return $query->result();
}
It runs this query:
SELECT * FROM FYP_Milestones INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID WHERE FYP_Milestones.MilestoneDue < 2016-04-14 ORDER BY FYP_Milestones.MilestoneDue ASC
I have a row in the database like so:
Considering 2016-04-07 is less than 2016-04-14 by 7 days I'm expecting that row alone to be pulled, but SQL is returning an empty result , why is this the case?

You actually don't need PHP for the range, use SQL:
WHERE FYP_Milestones.MilestoneDue < (CURDATE() + INTERVAL 2 WEEK)

Add single quotes to the date value like:
$query = $this->db->query("SELECT * FROM FYP_Milestones
INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID
WHERE FYP_Milestones.MilestoneDue < '".$range."'
ORDER BY FYP_Milestones.MilestoneDue ASC
");

Related

PHP SELECT to query date field plus 6 hours

I would like to query a date field to select all entries that are equal to or greater than current time + 6 hours. The commented first entry works, but it is the second entry that I am battling with. I know this syntax is nowhere near correct.
//$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND date_added >= CURRENT_DATE ORDER BY order_id DESC";
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND CURRENT_TIME >= date_added +6 hours";
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND NOW()>= DATE_ADD(date_added,INTERVAL 6 HOUR)";
This query will get your date_added value and add 6 hours to it and after will compare it with the CURRENT_TIME. I would suggest to use NOW() instead of CURRENT_TIME in mysql.
You're probably looking for the DATE_ADD (documentation) function. In your case:
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND your_date_field >= DATE_ADD(CURRENT_TIME, INTERVAL 6 HOURS)";
would likely do what you need it to.
try this query
$query = "SELECT * FROM `order` WHERE order_status_id = 1 AND CURRENT_TIME >= DATE_ADD(date_added, INTERVAL 6 HOUR)";

SELECT count from multiple tables between 2 dates with BIG DATA

I have multiple tables (same column structures) which I want to have the count rows between 2 date ranges. Right now it gives me all records from each table. Each table have around 700K records, which makes it also slow to search through.
I'm not getting the right query for this.
The below query is what I have so far.
$monday = '2018-01-15';
$tuesday = '2018-01-16';
SELECT count(datetime) FROM uptime_m1 WHERE datetime
BETWEEN '$monday' and'$tuesday' and status = 'idle'
UNION ALL
SELECT (datetime) FROM uptime_m2 WHERE datetime
BETWEEN '$monday' and'$tuesday' and status = 'idle';
PHP CODE:
if ($result = $mysqli->query("
SELECT count(datetime) FROM uptime_m1 WHERE datetime
BETWEEN '$monday' and'$tuesday' and status = 'idle'
UNION ALL
SELECT (datetime) FROM uptime_m2 WHERE datetime
BETWEEN '$monday' and'$tuesday' and status = 'idle';
")) {
$row_cnt = $result->num_rows;
$count_m1_idle_monday = $row_cnt;
$result->close();
}
You can use a subrequest to count each table and sum the result.
select
(select count(*) from uptime_m1
where datetime between '$monday' and '$tuesday' and status = 'idle')
+ (select count(*) from uptime_m2
where datetime between '$monday' and '$tuesday' and status = 'idle')
as nbrows;

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.

Calculating data from one DB table with range of dates

I have sql function:
$sql = "SELECT date(datum_ura) as datetime,
COUNT(CASE rezultat_status_fk WHEN 5 THEN rezultat_status_fk END) AS half_lost, AVG(kvota) as average, SUM(vlozek) as vlozek,
SUM(CASE rezultat_status_fk WHEN 1 THEN vlozek * kvota WHEN 2 THEN vlozek WHEN 3 THEN 0 END) AS case_profit,
SUM(CASE rezultat_status_fk WHEN 1 THEN vlozek * kvota-vlozek WHEN 2 THEN 0 WHEN 3 THEN -vlozek END) AS profit
FROM bs_analiza
WHERE users_fk=$user_id"." group by date(datum_ura)";
The function is getting data from one table and calculates it and show results by dates. I'm trying to do a function which can sum current date result with the day before result....and so on.
I'm thinking of something like:
foreach ($items as $key => $value) {
$date = $value->datetime;
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$prev_date = strtotime($prev_date);
$i = $key-1;
$profit_before = $items[$i]->$prev_date;
But I'm still getting the same results.
You can achieve this with selects from your intermediate result, I suggest you either create a view or use WITH.
SELECT
datetime,
(SELECT SUM(vlozek) FROM ... WHERE datetime >= t.datetime) vlozek_cumsum,
(SELECT SUM(case_profit) FROM ... WHERE datetime >= t.datetime) case_profit_cumsum,
(SELECT SUM(profit) FROM ... WHERE datetime >= t.datetime) profit_cumsum
FROM
... t
ORDER BY
datetime DESC
... is your intermediate result.
Edit (to clarify): You get your intermediate result by a select statement. So you can either
Create a view and replace ... by the name of the view or
CREATE OR REPLACE VIEW <view_name> AS <select_stmt>
Use WITH and replace all ... in the query above by the alias name.
WITH <alias_name> AS ( <select_stmt> )
SELECT
...

Reduce number of mysql count query for different time interval

I am using below query:
$select_jan1 = "SELECT count(*) FROM users WHERE timeStamp BETWEEN '2015-01-01' and '2015-01-31'";
$select_feb1 = "SELECT count(*) FROM users WHERE timeStamp BETWEEN '2015-02-01' and '2015-02-28'";
$select_mar1 = "SELECT count(*) FROM users WHERE timeStamp BETWEEN '2015-03-01' and '2015-03-31'";
Is there way to put this 3 query in one ?
Thank You
You can put the values in three columns, using conditional aggregation:
SELECT SUM(timeStamp BETWEEN '2015-01-01' and '2015-01-31') as cnt_201501,
SUM(timeStamp BETWEEN '2015-02-01' and '2015-02-28') as cnt_201502,
SUM(timeStamp BETWEEN '2015-03-01' and '2015-03-31') as cnt_201503
FROM users;
Do note that this logic ignores that values on the last day of each month. Better logic is:
SELECT SUM(timeStamp >= '2015-01-01' and timestamp < '2015-02-01') as cnt_201501,
SUM(timeStamp >= '2015-02-01' and timestamp < '2015-03-01') as cnt_201502,
SUM(timeStamp >= '2015-03-01' and timestamp < '2015-04-01') as cnt_201503
FROM users
WHERE timeStamp >= '2015-01-01' and timeStamp < '2015-04-01';
With whole months, I do so:
SELECT
count(*)
FROM
(SELECT
year(timestamp) AS year_, month(timestamp) AS month_
FROM
users) s
WHERE
s.year_ = 2015 AND s.month_ >=4

Categories