change sql query to find data between a date range [duplicate] - php

This question already has answers here:
MySQL Check if date range is in date range
(2 answers)
mysql : check date range
(2 answers)
Closed 4 years ago.
I have the following code, and it's working fine:
$time = time();
$todayint=date("Y-m-d", strval($time));
$sql = "SELECT * FROM " . $DB->prefix('cal_event') . " WHERE DATE(FROM_UNIXTIME(event_start))='$todayint' OR DATE(FROM_UNIXTIME(event_end))='$todayint' ORDER BY event_organiser ASC";
How do I change the code to select data between a date range?
event_start and event_end are stored as int.
I tried using between but I'm not sure where exactly to put between in the code.

For queries against a single date field, you can make use of the BETWEEN operator:
$sql = "SELECT * FROM " . $DB->prefix('cal_event') . " WHERE
DATE(FROM_UNIXTIME(event_time)) BETWEEN '$date1' AND '$date2'
ORDER BY event_organiser ASC";
And for queries against multiple date fields (like both the start time and end time), you'll want to check => and <=:
$sql = "SELECT * FROM " . $DB->prefix('cal_event') . " WHERE
DATE(FROM_UNIXTIME(event_start)) >= '$todayint' AND
DATE(FROM_UNIXTIME(event_end)) <= '$todayint'
ORDER BY event_organiser ASC";
In both cases you'll want to make use of AND rather than OR.

Using BETWEEN (column BETWEEN value1 AND value2)
$time = time();
$todayint=date("Y-m-d", strval($time));
$sql = "SELECT * FROM " . $DB->prefix('cal_event')
. "WHERE DATE(FROM_UNIXTIME(event_start))
BETWEEN '$todayint' AND '$todayint'
ORDER BY event_organiser ASC";
Using >= (column >= value1 AND column <= value2)
$time = time();
$todayint=date("Y-m-d", strval($time));
$sql = "SELECT * FROM " . $DB->prefix('cal_event')
. "WHERE DATE(FROM_UNIXTIME(event_start)) &gt= '$todayint'
AND DATE(FROM_UNIXTIME(event_end)) &lt= '$todayint'
ORDER BY event_organiser ASC";

Related

php and mysql query to get date of the last 12 months

I have a php function to get dates for a morris pie chart and it was working fine.
But now that I have more data (date for the last year and the first 3 months of this year). It's now displaying duplicate months. In this case february of last year and this years data is now showing on the same pie chart.
I'd like to write a some mysql code in php that will only display the last 12 months. I have the following code:
function writesql($rec) {
$year = date('Y') -1;
$month = date('m');
$lastyear = $year - $month; // I know this is a problem.It's subtracting the two variables
$sql = "";
$sql = $sql . " SELECT";
$sql = $sql . " YEAR(`value`)as 'Year',";
$sql = $sql . " MONTH(`value`)as 'Month',";
$sql = $sql . " `value` , ";
$sql = $sql . " COUNT(`value`) as 'Calls' ,";
$sql = $sql . " ROUND(SUM( `value` ),2) as 'Value'";
$sql = $sql . " FROM `table`";
$sql = $sql . " GROUP BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)" ;
$sql = $sql . " ORDER BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)";
$sql = $sql." WHERE (`value`)='".$lastyear."'";// I also know this is wrong too but im lost as to how to fix it.
return $sql;
}
Then the rest follows, I only want to get the data for the last 12 months how should I be executing this.
You could do WHERE value >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR);
This would show 12 months up to the current date.
You are close. Make these changes
$year = date('Y') -1; // This will give last year
$sql." WHERE YEAR(`value`)='".$year."'"
Updated Query
$sql = "
SELECT YEAR(`value`) as 'Year', MONTH(`value`) as 'Month', `value`,
COUNT(`value`) as 'Calls', ROUND(SUM( `value` ),2) as 'Value'
FROM `table`
WHERE YEAR(`value`) = '$year'
GROUP BY YEAR(`value`), MONTH(`value`)
ORDER BY YEAR(`value`), MONTH(`value`)";
First off, I find this easier to read:
$sql = "
SELECT YEAR(value) Year
, MONTH(value) Month
, value
, COUNT(value) Calls
, ROUND(SUM(value),2) Value
FROM `table`
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value)
WHERE (value) = '".$lastyear."'
";
But this query is syntactically incorrect. So here's a syntactically correct version:
$sql = "
SELECT YEAR(`value`) Year
, MONTH(`value`) Month
, COUNT(value) Calls
, ROUND(SUM(value),2) Total_Value
FROM `table`
WHERE value = '".$lastyear."'
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value);
";
Now see about prepared and bound queries

MySQL query with date parameter

My table in mysql has special data stamp (startdata). It is date when event starts. Older events stored in database to, but i don't need them to appear in the MySQL answer.
So is there any way sending query to database that includes parameter i need? (for example, not showing rows where startdate older than today).
Now my code looks like:
$res3 = mysqli_query($con,"SELECT * FROM raspisanie WHERE
instr='" . $instrument . "' AND school IN(" . $array2 . ")
AND type='regular' AND state='1' ORDER by startdate");
Add condition in your where clause.
$res3 = mysqli_query($con,"SELECT * FROM raspisanie WHERE
instr='" . $instrument . "' AND school IN(" . $array2 . ")
AND type='regular' AND state='1' AND startdate >now() ORDER by startdate");

how to hide the data whose date have been passed

I want to hide the date which have been passed.
"SELECT * FROM " . USER_TABLE_NAME . " AS cu
INNER JOIN " . JOB_TABLE_NAME . " AS jb
ON jb.user_id = cu.user_id
WHERE cu.user_id = '$userID'
ORDER BY jb.job_date DESC, jb.job_tea_time DESC";
Rightnow I'm getting all the data order by date.
The date is stored in VARCHAR and i am not suppose to change that.
Thanks,
I think this will be helpful
"SELECT * FROM " . USER_TABLE_NAME . " AS cu
INNER JOIN " . JOB_TABLE_NAME . " AS jb
ON jb.user_id = cu.user_id
WHERE cu.user_id = '$userID' AND STR_TO_DATE(jb.job_date,'%d/%m/%Y') >= now()
ORDER BY jb.job_date DESC, jb.job_tea_time DESC;
You can use strtodate function to convert the string to date - afterwards you can easily compare it via date functions.
You can convert date string (varchar) to unix timestamp using mysql function unix_timestamp and for comparison less than today's date , you can use strtotime('today') in php
"SELECT * FROM " . USER_TABLE_NAME . " AS cu INNER JOIN " . JOB_TABLE_NAME . " AS jb
ON jb.user_id = cu.user_id
WHERE cu.user_id = '$userID' AND unix_timestamp(jb.jobdate) > " . strtotime('today') . "
ORDER BY jb.job_date DESC, jb.job_tea_time DESC";
This should work. If found any issue, let me know!

Count records from multiple tables in real-time

I want to count a record by current date from different tables and return as one row with different column in the new table. The code will update a record every three hours and insert new record if current date changes. I've current date and time data (2013-05-20 14:12:12) in "created_at" column. Here my current code:
require_once('./db_connect.php');
$dbcon = new db;
//test to see if a specific field value is already in the DB
public function in_table($table,$where) {
$query = 'SELECT * FROM ' . $table . ' WHERE ' . $where;
$result = mysqli_query($this->dbh,$query);
$this->error_test('in_table',$query);
return mysqli_num_rows($result) > 0;
}
//running in background
while (true) {
$select= "SELECT (SELECT CURDATE()) AS time," .
"(SELECT COUNT(tweet_id) FROM tweets WHERE created_at= 'CURDATE() %') AS total_count," .
"(SELECT COUNT(fid) FROM fun WHERE ftime= 'CURDATE() %') AS f_count," .
"(SELECT COUNT(sid) FROM sad WHERE stime= 'CURDATE() %') AS s_count";
$results = mysqli_query( $dbcon, $select );
while($row = mysqli_fetch_assoc($result)) {
$time = $row['time'];
$total = $row['total_count'];
$fcount = $row['f_count'];
$scount = $row['s_count'];
$field_values = 'time = "' . $time . '", ' . 'total_count = ' . $total . ', ' . 'fun_count = ' . $fcount . ', ' . 'sad_count = ' . $scount;
if ($dbcon->in_table('count','time= "' . $time . '"')) {
$update = "UPDATE count SET $field_values WHEN time= '$time'";
mysqli_query( $dbcon, $update );
}
else {
$insert = "INSERT INTO count SET $field_values";
mysqli_query( $dbcon, $insert );
}
}
//update record every 3 hour
sleep(10800);
}
With this code I can't get a count record. The result return | 2013-05-18 | 0 | 0 | 0 |. How can I correct this?
I not familiar with PHP, but you can retrieve the count of all records dated any time today using:
SELECT COUNT(tweet_id)
FROM tweets
WHERE created_at >= curDate()
AND created_at < date_add(curDate(), interval 1 day)
It is equivalent to saying
..
WHERE created_at >= (today at midnight *incusive*)
AND created_at < (tomorrow at midnight *exclusive*)
Update:
The advantage of this method is it is index friendly. While using WHERE DATE(Column) = currDate() works, it can prevent the database from using indexes on that column, making the query slower.
Replace the parts where you have this:
WHERE created_at= 'CURDATE() %'
with this:
WHERE DATE(created_at) = CURDATE()
Your existing WHERE clause is comparing created_at to the string constant CURDATE() %, and they'll never match.
You are comparing against created_at= 'CURDATE() %', which is looking for that exact string, not for the result of a function. If the field created_at is a date, it will never match.
And, you are doing that for all counts.

Select data between two dates?

I'm using a database to store logs, with a column "date" which holds the date it was inserted. The format of the date is "MM/DD/YY". Please can anyone suggest how I would SELECT data in between two certain dates. For example, I tried this:
$from_date = "01/01/12";
$to_date = "02/11/12";
$result = mysql_query("SELECT * FROM logs WHERE date >= " . $from_date . " AND date <= " . $to_date . " ORDER by id DESC");
while($row = mysql_fetch_array($result)) {
// display results here
}
But I guess this doesn't work because the dates aren't numbers. Thanks for the help! :)
Use the BETWEEN keyword:
"SELECT * FROM logs WHERE date BETWEEN '" . $from_date . "' AND '" . $to_date . "'
ORDER by id DESC"
You can cast the fields as dates and then select between from_date and to_date
SELECT * FROM logs WHERE date STR_TO_DATE(date, '%m/%d/%Y') between STR_TO_DATE(from_date, '%m/%d/%Y') and STR_TO_DATE(to_date, '%m/%d/%Y')
The answer to your question depends on the data type that is used to store the date field in the logs table.
SQL (MySQL in your case) is fully capable of comparing dates. Usually, the BETWEEN .. AND .. operator is used but that will not work correctly if the type of date is CHAR (or VARCHAR) - in which case you will need to cast the date field to a DATETIME before comparing.
You need to add single quotes to the date values '01/01/12':
$from_date = "01/01/12";
$to_date = "02/11/12";
$result = mysql_query("SELECT * FROM logs WHERE date >= '" . $from_date . "' AND date <= '" . $to_date . "' ORDER by id DESC");
Change date parameters into Unix timestamps and then compare them. Here is the code:
$from_date = "2019/01/12";
$to_date = "2019/01/15";
$from_date_unix = strtotime($from_date);
$to_date_unix = strtotime($to_date);
$result = mysql_query("SELECT * FROM logs WHERE date >= " . $from_date_unix . " AND date <= " . $to_date_unix . " ORDER by id DESC");
while($row = mysql_fetch_array($result)) {
// display results here
}

Categories