PHP Oracle substraction from current row with previous row - php

I have data like below:
Time | Count
17:31:49
17:35:52
17:36:54
17:38:12
17:39:12
17:40:12
17:41:57
17:43:47
17:45:27
17:48:12
17:48:17
Now I need to subtraction current row with previous row.
So this will be like this:
Time | Count
17:31:49 formula: 17:35:52 - 17:31:49 = 04:03
17:35:52 formula: 17:36:54 - 17:35:52 = 01:02
17:36:54 formula: 17:38:12 - 17:36:54 = 01:58
17:38:12 and so on
17:39:12
17:40:12
17:41:57
17:43:47
17:45:27
17:48:12
17:48:17
Is it possible to do the calculation only using query or need PHP (I'm using this) to do that?

Basically, you can use lead():
select time, lead(time) over(order by time) - time diff
from mytable
It is unclear what the datatype of time is. If it is a DATE, then you can substract, and you get a decimal number representing the difference in days; you can format or use arithmetics to get the results you desire.
If it is of some other datatype (a string?), then you need to build your own logic to handle the substraction.

Related

php mysql select date from 1 day ago, upto the minute

I want to capture data that took place at the same hour and minute 24 hours ago. the formula below does not work. what could be the truth?
I will draw the date range in a single line, not listing.
$now=time();
$24hrb=$now-(24*60*60);
$que = $connc->query("select * from table where datetime='$24hrb';")
In my opinion it would be best to do this all in SQL. You can use the mysql intervals options to reduce by 1 day then like and substr to trim the seconds off and only pull the datetime through the minute value.
select * from table where datetime like concat(substr((now() - interval 1 day), 1, 16), '%')
The substr is taking from a string like this:
2021/01/22 11:12:21
^ ^
and concat throws the wildcard on the end so anything after that matches. So your like is processed as:
2021/01/22 11:12%
$24hrb=time() - (24*60*60);
This is a Timestamp value. But you state in comments:
yes. datetime format Y-m-d H:i:s
So what you actually should be doing if you insist on using this method is converting your datetime to a Unix timestamp:
$que = $connc->query("SELECT * FROM table
WHERE UNIX_TIMESTAMP(`datetime_column`) = '".(int)$24hrb."'");
This is much better and easier to read than messing around with concatenations and string manipulations.
Further,
You can extend this action using the MySQL BETWEEN keyword so that you can get the values found between the range of times, say +/- 30 seconds. so:
$que = $connc->query("SELECT * FROM table
WHERE UNIX_TIMESTAMP(`datetime_column`)
BETWEEN ".($24hrb - 30)." AND ".($24hrb + 30));

How to check if time intervals are overlapping in Laravel 4.2/php?

So i have in a table tm_timekeep(id(pk), start(varchar), end(varchar)) [and a model for it] in a database with some time intervals in HH:MM format. For example:
id|start|end |
---------------
0 |10:00|10:30|
1 |11:23|11:55|
2 |13:15|15:39|
i would like to insert new rows and modify the existent ones if there are no overlappings between intervals.
if i would like to add as interval 11:57-12:40 would be ok, but 09:00-10:20 wouldn't because of 10:00-10:30, same for updateing a row. And if i would like to update a row, I need a function to check the condition before modifying the row. How should i do this?
My current code snippet:
public function checkInterval($start, $end){
$counter = 0;
$timekeepArray = Timekeep::all();
$start = date('H:i',Input::get('start'));
$end = date('H:i',Input::get('end'));
foreach($timekeepArray as $timekeep)
{
if($start <= $timekeep->end && $end>=$timekeep->start){
counter++; //in range
}
return counter;
}
}
After this i check the value of counter, but my problem is, that i always get 0 even if there are overlappings from input.
It's quite trivial - convert your time intervals to minutes, eg. 10:00 becomes 10 * 60 + 0 = 600 minutes, ends at 630 correspondingly.
Then, when you are trying to insert or update, and I would suggest you do it in Timekeep model, bound to 'saving' model event (see Model Events), you check whether:
1) Pick the last end time in minutes that is less than your new start time (that's a trivial SQL query)
2) See if there is any existing time in between that end time and your new end time - if there is, we have overlapping. Throw an exception, cancel model saving
There are several ways you could convert strings to minutes - you could store integers in MySQL (eg. 600) and then convert them to human readable hours either by defining getAttribute() or making your own methods. Or you could keep storing data as VARCHARs and do simple string manipulations (remove ':', multiply first part by 60) either in SQL or in PHP

need to convert data and time values to microtime

have a database with data and time
example: 2013-06-04 08:20:00
need to convert that to
example: 1378478351000
so i can add that number to jquery script event calendar
when i use this php code
$exc_date = $row_Recordset1['exc_date'];
$exc_date = microtime(true) *1000 ;
echo $exc_date;
it works right but it shows me the current date and time not the date and time saved at database,
can somone please help , thanks
If you want to avoid the calculations in PHP, add a computed column using unix_timestamp and str_to_date to your query:
select (
unix_timestamp(str_to_date(TimeStrColumnName, '%Y-%m-%d %H:%i:%s')) * 1000)
as utime,
# ... the rest of your query as before
if the MySQL column is already a date/time field (instead of a string), this will do it:
select (unix_timestamp(TimeStampColumnName) * 1000) as utime,
# ... the rest of your query as before
Of course it does, as you overwrite the database values in the second line by putting microtime instead in it.
You will not be able to get the microtime, when you just have the format of date in the database - so you should use 0. microtime is returning the value of the actual microtime at the moment.
You should do something like that to get time + microtime:
$exec_date = strtotime($row_Recordset1[exec_date"]) . "000";
More information here. The problem with this is, that you will get it as a string, so you will need to convert it to an integer:
$exec_date = (int) $exec_date;
Hope it helps you.

How to input time from <select> into mysql and have it output am/pm?

Hey guys so, im doing this form with a input that will contain the time and i want to make it so that when users choose the time (for example 8:30 AM), it will be stored in mysql, and will be output by php with the exact time (8:30 AM).
Here is the form. A simple select button with increments of 30 on the time.
http://jsfiddle.net/jXVPS/
The main problem is i dont know how mysql will recognize if it is AM/PM?
What values i should put for the select fields, how i would insert it into the mysql database, and have mysql or php recognize wheather it is 1:00 AM or 1:00 PM. Is there some sort of 24 hour clock in mysql that makes it recognize wheather or not it is AM/PM?
Use TIME column type:
TIME
A time. The range is '-838:59:59' to '838:59:59'. MySQL displays TIME values in 'HH:MM:SS' format, but allows you to assign values to TIME columns using either strings or numbers.
It will parse the values in your select options nicely.
Edit: Example of use:
// saving in the db
$sql = "
INSERT INTO table_name SET
# ...
name_of_the_time_column = '" . mysql_real_escape_string($_POST['start_time']) . "'";
// retrieving from the db
$sql = "
SELECT id, ..., TIME_FORMAT(name_of_the_time_column, '%h:%i:%s %p') AS formatted_time
FROM table_name
# ...
";
Here's MySQL's time/date stuff. I think the TIME type would be best for you since you don't need a date, and the format you've got for your values should fit well. I think you can just put them as strings exactly like that.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html
After you submit thru form submission or ajax and your responding PHP page takes over, perform a query with the following string in the PHP:
"INSERT INTO table (userId, time, ...) VALUES (..., '$inTime', ...)"
And then echo it out since you want the next page to repeat it.
Response to comment
I figure you mean that wou want 13:00:00 to be 1:00 PM when you echo it out later right?
Theres probably something you can do with time functions for either PHP or MySQL (PHP below, MySQL above), but I don't know from memory and this is simple enough you can just do it on your own.
http://www.php.net/manual/en/ref.datetime.php
$time = //get time field from MySQL
list($h, $m, $s) = explode($time, ':');
if ($h > 12) {$h -= 12; $amOrPm = 'PM'}; else {$amOrPm = 'AM';}
if ($h == 0) {$h = 12;}
echo "$h:$m $amOrPm";
PS - 13:00:00 is 1pm, not am.
Not tested :
INSERT INTO myTable
SET time = TIME(STR_TO_DATE('8:30:00 AM','%h:%m:%s %p'))

How to extract only Hour data from PHP Time string?

I have a collection of time records in a database in the format '09:51:06' (hour, minute, second).
I have a query which retrieves a bunch of these times from the database, but I only care for the Hour reference.
How can I get rid of the rest of the string and ad just the hour into an array? So in the example above, I just want to keep '09'.
I've looked into exploding and substrings, but can't seem to figure it out.
Thanks.
Exploding the string would look like this (you probably want to add intval() to be able to use it as a real number):
$hours = array_shift(explode(':', '09:51:06'));
But you are probably looking for the right query instead of doing this afterwards. If you are dealing with a time-type, you can use MySQL's date and time functions (HOUR() in this case):
SELECT HOUR(`time_column`) AS `hour` FROM `your_table`
Or from the database itself
SELECT TIME_FORMAT(field_name, '%H') as return_hour from table_name
$time_string='09:51:06';
$your_array[$array_index]=substr($time_string, 0, 2);
for more info on substr
I guess you can do this either thru string manipulation or time/date. Any worthwhile date way would be on the SQL side, PHP has mktime and date functions but you would have get the hour you're looking for intermediately along the way if you were to construct a date anyway
String
$thisHour = array_shift(explode(':', $timeString)); //this gets hour
$thisHour - substr($timeString, 0, 2); // or this
$hours[] = $thisHour; //this adds to array

Categories