Adding two times from database - php

im a newbie in PHP and im trying to solve this situation as much as i can but still don't get/know the right answer.
I have a table with 2 columns in database with time datatype
Lunch Break
00:01:00 00:00:30
Im trying to fetch the data and add the two times, but i always get the wrong value.
I have this code:
$time[$x] =$row['break'] + $row['lunch'];
$totalAux[$x] = $time[$x];
Output is : "00:00:00"
The i try this one:
$time[$x] =strtotime($row['break']) + strtotime($row['lunch']);
$totalAux[$x] = $time[$x];
And get an ouput of "00:00:00"
Then lastly tried this one:
$time[$x] =strtotime($row['break']) + strtotime($row['lunch']);
$totalAux[$x] = date('H:i:s', $time[$x]);
Output was: "09:33:14"
Please Help Guys .

You can use ADDTIME function from MySQL:
SELECT Lunch, Break, ADDTIME(Lunch, Break) FROM table_name;
sqlfiddle

Why don't you use the TIMEDIFF() and ADDTIME() functions which is to get the difference or to add times respectively in mysql so that it would be resolved there and php will just have to pick it up.
You need to use also TIME_FORMAT() in order to get the hours, minutes and seconds:
SELECT TIME_FORMAT(ADDTIME(lunch, breaks),'%H:%i:%s') as TimeTotal
FROM lunchbreaks;
SELECT TIME_FORMAT(TIMEDIFF(lunch, breaks),'%H:%i:%s') as TimeDifference
FROM lunchbreaks;
See the Demo

Related

Converting Excel formula to PHP or MySQL Query

I'm trying to convert an excel scoring program and this one formula is driving me nuts. so this is the excel formula =IF(AD4<AE4,AE4-AD4,0) and I have been stumped for a little bit. I have looked at, and tried a few sample formulas for both PHP & MySQL, but I keep receiving syntax errors, unexpected if or else in the code.
So what the formula is checking to see if the elapsed time is under a set time, and if so, calculates the difference between the 2 fields and displays the outcome in time format hh:mm:ss.
This is the latest SQL query I tried:
Select *
if (`Under Time`<`Speed Fault`,0)
else { (`Time Elapsed`-`Speed Fault`)} As Under Time
from time_db
In sql , you can use case :
Select *,case when (UnderTime<SpeedFault)
then 0
else TimeElapsed - SpeedFault end As UnderTime
from time_db
SELECT *,
GREATEST(`Time Elapsed`-`Speed Fault`, 0) AS `Under Time`
FROM time_db;

Select month from a date field in laravel

I'm trying to perform a query in Laravel 7 that gets the month part of a date field. I tried the following queries
$test = MyModal::selectRaw('month("date_col") as temp')->get();
$test = MyModal::select(DB::Raw('month("date_col") as temp'))->get();
$test = DB::table('my_table')->select('month("date_col") as temp')->get();
All variation of the same query. If I dump the query log, the query is correct for all 3
select month("date_col") as temp from "my_table"
If I run this on my DB I get the result as well. But I keep getting this error in laravel:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such function: month (SQL: select month("date_col") as temp from "my_table")
Am I doing something wrong? And is there a way to do this query in laravel?
Edit: Sorry forgot to mention this is with Laravel's unit testing
I think the problem in the way you use Month function
you don't set quotations for the column name, it should be:
$test = MyModal::selectRaw('month(date_col) as temp')->get();
it should work
You can do something like this:
MyModal::select(DB::raw("MONTH(date_col) month"))->get();
Thanks to OMR's comment this solution finally worked
$test = MyModel::selectRaw('strftime("%m", "date_col") as temp')->get();
Update: It looks like what I had in the beginning worked fine and the unit test was the only part throwing this error. Since I was working with mysql while the test environment was using sqlite which apparently doesnt like the "month()" function which OMR did point out in his comment. So this solution works in the test but not in live. Couldn't figure out how to change the test environment to use in memory mysql instead of sqlite. If anyone knows how to please add an answer here.

PHP, Add gmdate to gmdate

I have a code that looks like this:
$dagtidhelg = gmdate('H:i', $diffMorning) . "\n";
$kvallstidhelg = gmdate('H:i', $diffNight);
This code runs several times per page since its runt every time a row is loaded from mysql.
It can return a time value ie 08:15 and 09:30. This is the lenght of two work sessions.
That works great but now Im stuck, I want to display the total of every work session at the bottom. I have tried this:
$dagtidhelgtotal = $dagtidhelgtotal + $dagtidhelg;
$kvalltidhelgtotal = $kvalltidhelgtotal + $kvallstidhelg;
But that only adds the hours togheter, it wont even display the :
So Im guessing that Im doing this totaly wrong.
How can I add these times togheter? Maybe convert them to minutes, then add them all togheter?
Add duration together is simple .But you must keep in mind that duration and date are two things completely different. You can write 100:08 for duration but not for date. If your purpose is to keep a duration counter on(one or) every page(s) you need to build a system based on $_SESSION variable.
To add two duree you can proceed like this:
function addDuration($duration1,$duration2){
$result=array_map(function($x,$y){return sprintf("%'.02d", $x+$y);},explode(':',$duration1),explode(':',$duration2));
if($result[1]>60){
$result[0]=sprintf("%'.02d",$result[0]+(int)$result[1]/60);
$result[1]=sprintf("%'.02d",$result[1]%60);
}elseif($result[1]==60){
$result[1]="00";
$result[0]=sprintf("%'.02d",$result[0]+1);
}
return join(':',$result);
}
and the usage in your case could be:
$dagtidhelgtotal = addDuration($dagtidhelgtotal,$dagtidhelg);
if we suppose that
$dagtidhelgtotal ==='100:09' && $dagtidhelg === '08:08'
then after the addition
$dagtidhelgtotal will be equal to '108:17';

MySQL query with date ranges returning no results

So I am doing this query from PHP, and here listerally the exact query string:
SELECT * FROM `pdem_timesheet`.`tblMasterTimesheets` WHERE
`pdem_timesheet`.`tblMasterTimesheets`.`username` = 'pdem' AND
`pdem_timesheet`.`tblMasterTimesheets`.`date` >= '2012-05-09' AND
`pdem_timesheet`.`tblMasterTimesheets`.`date` <= '2012-05-15' ORDER BY
`pdem_timesheet`.`tblMasterTimesheets`.`date` ASC
It looks like it should be correct to me (more-or-less copying it from previous code I used that DOES work). But when I run the query, the results are empty.
If I change the query to not be a date range, but just a single day:
SELECT * FROM .... WHERE ...`date` = '2012-06-12' ....
it works just fine, returns the one result that it should.
I have tried using the between keyword:
SELECT * FROM ... WHERE ...`date` BETWEEN [start] [end]
but it still returns nothing...
Any ideas how to get this query to return a result?
===ANSWER===
When you go:
var curr_date = now.getDate();
var curr_month = now.getMonth();
var curr_year = now.getFullYear();
it returns the month - 1 for some reason. So if now's month is 6, now.getMonth() will return 5...Just need to add 1 in the query (wish I saw this sooner)
Your query seems to be working for me.
See demo.
Query I have is
SELECT * FROM tblMasterTimesheets
WHERE
username='pdem'
AND
date >= '2012-05-09' AND
date <= '2012-05-15'
ORDER BY date ASC
I assume, username is of type varchar and date is of type timestamp or datetime.
Similar to Fahim Parkar, here is an example of your query working with the use of the BETWEEN syntax: http://sqlfiddle.com/#!2/0fcb5/4
It sounds like your user pdem does not exist.
Make sure that:
There is in fact a result which should be returned when using your
given criteria. Make sure the DD-MM-YYYY syntax is correct and make sure you know which month is which number (may is 05, june is 06)
That the datatype of the column date is of a date
type, not a generic text/varchar type. You cannot compare varchar with >= like that (not the way you want, at least. Only works on date types)
As Fahim said, your code is correct. It must be something within the table which is causing your issues.

Removing rows from MySQL table where the timestamp is over one day old?

I found the exact same question here.
But it isn't working for me. I've modified it a bit, manipulated it, and I can't figure it out. I'm trying to remove rows that are over a day old. Here is my code:
if (isset($_POST['prune'])) {
$sql = "DELETE FROM logs WHERE time < date('now', '-1 days')";
mysql_query($sql);
echo 'Logs older than one day removed.';
}
Fairly simple question I suppose, but its bugging the hell out of me. I would appreciate any help.
In case it makes a difference, the column is a TIMESTAMP type.
EDIT: Apparently I'm an idiot. The question I linked you to relates to SQLite3. So now my question is, how can I do this in MySQL?
You can subtract an interval:
DELETE FROM logs WHERE time < now() - interval 1 day
That answer was IIRC for SQLite3. You're using MySQL which does not support this syntax.
You want to use DATE_ADD() function (example below not tested but should work):
DELETE FROM logs WHERE time < TIMESTAMPADD(DAY,-1,NOW());
In my case, only the
timestampadd
in positive direction works when running through an asc ordered date calendar:
if (urldecode ($aUrl['Select']) == '>')
$this-> db-> where ('konzertdatum >', 'TIMESTAMPADD(DAY, 1, "'. $id . '") ', false) ;
else
$this-> db-> where ('konzertdatum < ', 'TIMESTAMPADD(DAY, -1, "'. $id . '") ', false) ;
In negative direction (-1), the timestamp goes back to the very first entry. I also tried not to use CodeIgniter, but the same consequence.
Summing up, +1 as parameter for timestampadd works, -1 works for the second lowest entry (then jumping back to the first one. But it fails when I step further away from the first date.

Categories