SQL(mysql) comparing times not working - mysql

I am trying to select the message from a row where the start and end time is the same as $a and $b. But it does not bring any results however when i remove the end time it brings all the results.
I dont understand why its not working.
$a = '16:50:00';
$b = '17:00:00';
echo $times;
$query1 = ("SELECT message FROM db WHERE DATE(starttime) >= '$a' AND DATE(endtime) <= '$b'");

As you say the starttime and endtime columns are of type TIME. Running a DATE() on them will really mess the time up.
SELECT DATE('17:00:00);
will return 2017-00-00 i.e the best date it can make out of a time. Which of course is no use to you at all.
So mod your query to
SELECT message FROM db WHERE starttime >= '$a' AND endtime <= '$b'

Related

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

MYsql - Get average time between a start and stop time across many rows

I have the following SQL and PHP that doesnt seem to be giving me the right numbers. (VERY high numbers)
I have a lot of rows with a start time and an end timestamp.
Im looking to get the average time between those two times.
Ie: 2 hours, 3 minutes, 46 seconds.
This is what I have.
SELECT AVG(tmp.dd) AS timetook
FROM
( SELECT TIME_TO_SEC(TIMEDIFF(timeclosed, timeanswered)) AS dd
FROM logs
WHERE timeclosed > DATE_SUB(NOW(), INTERVAL 1 DAY)
) tmp;
Am I going about this the completely wrong way? Anything obviously wrong here?
while($row = $result->fetch_assoc()) {
$timetoclose = $row['timetook'];
$hours = floor($timetoclose / 3600);
$mins = floor($timetoclose / 60 % 60);
$secs = floor($timetoclose % 60);
$timetoclose = sprintf('%02d Hour(s), %02d Minute(s), %02d Second(s)', $hours, $mins, $secs);
}
Cheers
G
SELECT SUM(TIMESTAMPDIFF(minute, start_time, end_time)) / COUNT(*) AS avg_minutes
FROM your_table
try this query.

Total of all values in a day (24h)

I'd like to add all values in a database from the last 24 hours. Each value has its TimeStamp in the database.
I tried to do that with a for-loop, which adds 86400 secs (24h) every time, picks all values from one day and after that it adds all values.
Heres my code:
> `$datestart = 153839251200; //start date
for($uts = $uts; $uts > $datestart; $datestart + 86400){
if (($uts <= ($datestart + 86400)) && ($uts > $datestart)){
$uts = $datestart + 86400;
$valueFinal = $valueFinal + $value;
}
}
if($Zeitalt != $uts){
$Zeitalt=date('l, F j y H:i:s',$uts);
$uts *= 1000; // convert from Unix timestamp to JavaScript time
$data[] = array((float)$uts,(float) $valueFinal);
}`
I hope this explanation is enough, I'm not English speaking as much, otherwise just ask for more information.
Regards DR.Alfred
You've tagged this as SQL so I'm assuming an answer in SQL is what you're looking for.
Firstly, I'm not sure why you're going to the effort of using a loop to get the total when SQL has the SUM function.
I'll give you this in T-SQL as I'm not familiar with MySQL but it shouldn't be too difficult to change it to MySQL:
SELECT
SUM(YourValue)
FROM
YourTable
WHERE
YourTimeStamp > getdate() - 1
I think the MySQL equivalent of GETDATE() is NOW().

optimize sql query inside foreach

I need help optimizing the below querys for a recurrent calendar i've built.
if user fail to accomplish all task where date
This is the query i use inside a forech which fetched all dates that the current activity is active.
This is my current setup, which works, but is very slow.
Other string explained:
$today=date("Y-m-d");
$parts = explode($sepparator, $datespan);
$dayForDate2 = date("l", mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]));
$week2 = strtotime($datespan);
$week2 = date("W", $week2);
if($week2&1) { $weektype2 = "3"; } # Odd week 1, 3, 5 ...
else { $weektype2 = "2"; } # Even week 2, 4, 6 ...
Query1:
$query1 = "SELECT date_from, date_to, bok_id, kommentar
FROM bokningar
WHERE bokningar.typ='2'
and date_from<'".$today."'";
function that makes the foreach move ahead one day at the time...
function date_range($first, $last, $step = '+1 day', $output_format = 'Y-m-d' )
{
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
foreach:
foreach (date_range($row['date_from'], $row['date_to'], "+1 day", "Y-m-d")
as $datespan)
if ($datespan < $today)
Query 2:
$query2 = "
SELECT bok_id, kommentar
FROM bokningar b
WHERE b.typ='2'
AND b.bok_id='".$row['bok_id']."'
AND b.weektype = '1'
AND b.".$dayForDate2." = '1'
AND NOT EXISTS
(SELECT t.tilldelad, t.bok_id
FROM tilldelade t
WHERE t.tilldelad = '".$datespan."'
AND t.bok_id='".$row['bok_id']."')
OR b.typ='2'
AND b.bok_id='".$row['bok_id']."'
AND b.weektype = '".$weektype2."'
AND b.".$dayForDate2." = '1'
AND NOT EXISTS
(SELECT t.tilldelad, t.bok_id
FROM tilldelade t
WHERE t.tilldelad = '".$datespan."'
AND t.bok_id='".$row['bok_id']."')";
b.weektype is either 1,2 or 3 (every week, every even week, every uneven week)
bokningar needs INDEX(typ, date_from)
Instead of computing $today, you can do
and date_from < CURDATE()
Are you running $query2 for each date? How many days is that? You may be able to build a table of dates, then JOIN it to bokningar to do all the SELECTs in a single SELECT.
When doing x AND y OR x AND z, first add parenthes to make it clear which comes first AND or OR: (x AND y) OR (x AND z). Then use a simple rule in Boolean arithmetic to transform it into a more efficient expression: x AND (y OR z) (where the parens are necessary).
The usual pattern for EXISTS is EXISTS ( SELECT 1 FROM ... ); there is no need to list columns.
If I am reading it correctly, the only difference is in testing b.weektype. So the WHERE can be simply
WHERE b.weektype IN ('".$weektype2."', '1')
AND ...
There is no need for OR, since it is effectively in IN().
tilldelade needs INDEX(tilldelad, bok_id), in either order. This should make the EXISTS(...) run faster.
Finally, bokningar needs INDEX(typ, bok_id, weektype) in any order.
That is a lot to change and test. See if you can get those things done. If it still does not run fast enough, start a new Question with the new code. Please include SHOW CREATE TABLE for both tables.

Convert MySQL fetch array query to redbean PHP

I have 2 buttons which execute a post operations and set a hidden variable which is used to set the MySQL query to filter the database according to date
if result = today
$query = "SELECT id,customer_name,CAST( `register_date` AS DATE ) AS dateonly,status,
DATE_FORMAT(book_date, '%m/%d/%y') FROM table WHERE book_date
BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE()";
if result = week
$query = "SELECT id,customer_name,CAST( `register_date` AS DATE ) AS dateonly,status,
DATE_FORMAT(book_date, '%m/%d/%y') FROM table
WHERE book_date BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()";
I then want to use something like
$result=mysql_query($query);
while ($mytable=mysql_fetch_array($result))
{
loop and display all the information in array in a table
}
But I need the red bean equivalent of this.
The easiest way is to just paste the $query inside the sql function:
$results=R::getAll($query);
foreach($results as $row){
echo $row['id'];
}
The next way is to manually build the query.... which may just make it look sloppier in my opinion:
$results=R::$f->begin()->select('id, customer_name, CAST( register_date AS DATE ) AS dateonly,status, DATE_FORMAT(book_date, '%m/%d/%y')')->from('table')->where('book_date BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE())->get();
The final way is to grab results via redbean and handle them manually:
$results=R::find('table','book_date BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()');
Then loop through the results, configuring data along the way in php.
I always use this when I have to access a lot of data from mysql:
while ($row = mysqli_fetch_array($query)) { #converts query into array
$array[] = $row;
}
$array will be a multidimensional array. $array[x][column_name] will get you your data, x being the row which you want to access it from. Hope this helped.