SQL Query using DATE_ADD for time - php

Hey guys I've tried to figure this out,
I have
$query = "SELECT URL
FROM Matches
WHERE match_date = '" . $currentdate . "'
AND play_datetime < '" . $currenttime . "'
AND DATE_ADD(play_datetime, INTERVAL 3 HOUR) > '" . $currenttime . "'";
I can get the first AND to return, but the second part wont work where i have DATE_ADD, ive tried it by itself to return anything and i cant get it to work!
$current time right now is 06:01:14, its = date(h:i:s);
then in play_datetime it picks up the match_date lists a result, the time in play_datetime is 04:00:00

According to your query :
$currendate have date
and $currenttime have time.
But your column name "play_datetime" suggest that it is having datetime or timestamp .
so if this is right that your query is working but you have to put $currentdatetime instead of $currenttime.
$query = "SELECT URL
FROM Matches
WHERE match_date = '" . $currentdate . "'
AND play_datetime < '" . <timestamp> . "'
AND DATE_ADD(play_datetime, INTERVAL 3 HOUR) > '" . <timstamp> . "'";

Related

cannot get record which exist between a given time in codeigniter

I want to get records which exists between given start time and end time, start time and end time will be given by user, i'm using the following query for that :
$this->db->where('TIME(start) BETWEEN "' . date('H:i:s', strtotime($start_time)) . '" and "' . date('H:i:s', strtotime($end_time)) . '"');
$this->db->where('TIME(end) BETWEEN "' . date('H:i:s', strtotime($start_time)) . '" and "' . date('H:i:s', strtotime($end_time)) . '"');
$results = $this->db->get('class')->result();
start and end time column is datetime field:
eg. in database
start time : 2020-06-08 06:15:00
end time : 2020-06-08 09:15:00
#user3653474 You can use TIMEDIFF to check if the time provided is between the values of two columns or not. See if the query below does your deed.
$start = date('H:i:s', strtotime($start_time)); // get time from date in desired format
$end = date('H:i:s', strtotime($end_time));
// where $start is between column {start} and {end} AND $end is between column {start} and {end}
$sql = "SELECT * FROM class
WHERE (TIMEDIFF('$start', TIME(start)) >=0 AND TIMEDIFF('$start', TIME(end)) <= 0)
AND (TIMEDIFF('$end', TIME(start)) >=0 AND TIMEDIFF('$end', TIME(end)) <= 0)";
$results = $this->db->query($sql)->result();

Bulk MySQL update instead of PHP While loop

I am using PHP code to update week ending date which is on a different day for each subdomain. Each subdomain date range varies.
My current code uses a while loop to update the week end date. This is very slow and I am looking for ideas to optimise it.
Here is my current code:
// Loop through and assign week end date to each user activity.
$nextWeek = $startDate; // initialise while loop condition
while ($nextWeek <= $endDate) {
$lastWeek = $nextWeek;
$nextWeek = Carbon::parse($lastWeek)->addWeek(1)->format('Y-m-d');
// update activity date to week end date
$query = 'UPDATE r_active_user_activities
SET week_end_date = "' . $nextWeek . '"
WHERE (activity_date > "' . $lastWeek . '"
AND activity_date <= "' . $nextWeek . '"
AND subdomain="' . $subdomain->subdomain . '" );';
$db->statement($query);
}
Just append all those update queries in a php variable ($query) and execute that outside the while loop. something like this.
$nextWeek = $startDate; // initialise while loop condition
$query = '';
while ($nextWeek <= $endDate) {
$lastWeek = $nextWeek;
$nextWeek = Carbon::parse($lastWeek)->addWeek(1)->format('Y-m-d');
// update activity date to week end date
$query .= 'UPDATE r_active_user_activities
SET week_end_date = "' . $nextWeek . '"
WHERE (activity_date > "' . $lastWeek . '"
AND activity_date <= "' . $nextWeek . '"
AND subdomain="' . $subdomain->subdomain . '" );';
}
$db->statement($query);

DATE_ADD add month and day interval

So PHP does not accept doing something along the lines of:
$sql = "SELECT DATE_ADD('" . $this->db->escape($data['regpro_buy_date']) . "', INTERVAL " . $year_flag . " YEAR + INTERVAL " . $mon_flag . " MONTH) AS warranty_date; ";
but if I do:
SELECT NOW() + INTERVAL 2 YEAR + INTERVAL 2 MONTH
in MYSql it works fine. I am unsure of how to get it to where month and year are working together.
currently month and year are defined as:
$year_flag = 2;
$mon_flag = 3;
Hehe, nevermind, I was able to figure it out.
$sql = "SELECT DATE_ADD(DATE_ADD('" . $this->db->escape($data['regpro_buy_date']) . "', INTERVAL " . $year_flag . " YEAR), INTERVAL " . $mon_flag . " MONTH) AS warranty_date; ";

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
}

Only insert a row if for that day and that user, no row exists already

When someone visits X page for the first time, I insert a new row into the table with the current unix time()stamp.
I want to insert new rows, for that user, every 24 hours.. so for example:
Example A) Bob, goes to my site, it inserts a row.. 12 hours later, Bob comes back, it doesn't insert a new row as 24 hours haven't passed yet.
Example B) Bob, goes to my site, it inserts a row.. 24 hours later, Bob comes back, it DOES insert a new row as 24 hours HAVE passed.
I am toying around with this, but cannot think if this is right or not due to my brain being fried.
$time = time();
$difference = 86400;
$timedifference = $time + $difference;
When inserting the row:
mysql_query("INSERT INTO `logs` (`time`, `who`, `site`, `type`)
VALUES('" . $timedifference . "', '" . $ip . "', '" . $rid . "', 'out') ")
or die(mysql_error());
When checking to see if it has been 24 hours or more:
mysql_query("SELECT * FROM `logs`
WHERE `time` < '" . time() . "' AND `type` = 'out'
AND `site` = '" . $rid . "' AND `who` = '" . $ip . "'");
Can somebody please tell me if it's right?
Here is what I've come up with.. it seems to work:
//log check
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$time = time(); //current time
$difference = 86400; //one day in seconds
$timedifference = $time + $difference; //time difference
$logQ = mysql_query("SELECT * FROM `logs` WHERE `time` > '" . time() .
"' AND `type` = 'out' AND `site` = '" . $id .
"' AND `who` = '" . $ip . "'");
$logR = mysql_num_rows($logQ);
if ($logR <= 0){
mysql_query("INSERT INTO `logs` (`time`, `who`, `site`, `type`) VALUES('" .
$timedifference . "', '" . $ip . "', '" . $id . "', 'out') ") or
die(mysql_error());
}
Try
insert ignore into logs
select unix_timestamp(now()), who, site, type
from logs
where
who='{$ip}' and
site='{$rid}' and
type='out' and
unix_timestamp(time)<=unix_timestamp(now())-86400 limit 1;
And check if there a return affected_rows,
if so, meaning the new log added.
I would insert $time, rather than $timedifference.
You need to check to see whether time is less than time() - 86400. If you made time a datetime column, you could do this directly in the query.
In your last query you are not checking whether there is an entry over 24 hours old, you are only checking if there's an entry that is older than NOW.
Correct procedure is:
Create an index on the records for the login time.
SELECT the last record by this ascending index, for a user ('who').
If there is a last, and last is less than 24 hours away from now (time()), then skip creation of a new record.
Otherwise, create one for now (time()).

Categories