How to subtract two sql datetime fields - php

I have two datetime values on sql database and I want to subtract them and get the difference as a number of hours.
So far I have created three values. Deptime and ArrTime as datetime values and here are my questions.
1) What value shall the third table be? can it be number because I want to use it for statistics?
2) How can I subtract the Deptime and Arrtime and store the differnce in the FlightTime?
Thanks in advance

DATEDIFF can get you your hours.
SELECT DATEDIFF(HOUR, Deptime,Arrtime ) AS FlightTime FROM YourTable.

If you are using tSQL then you could use the DATEDIFF function. You can use this function with hours but if you want fractions of hours then you can use minutes and then convert back to hours.
fraction of hours
SELECT CAST(DATEDIFF(MINUTE, Deptime,Arrtime) AS DECIMAL(30,10))/60 AS FlightTime
FROM TableName
whole hours
SELECT CAST(DATEDIFF(HOUR, Deptime,Arrtime)) AS FlightTime
FROM TableName
Since it is a calculated field, I would just create a view with the DATEDIFF function for the calculated field.

PHP has its own DateInterval routines that might give you more flexibility (and portability) than doing it in SQL.
$datetime1 = new DateTime($DepDate);
$datetime2 = new DateTime($ArrDate);
$FlightTime = $interval->format('%h');
I'm looking at your progress and see a couple of red flags. Since you're accepting user input and inserting it into a database, you should at the very least be using prepared, parameterized insert statements.
$PiRepSubmissionSqlQuery = '
INSERT INTO Pireps (
PID, FLID, DEPID, ARRID,
FlightPlan, AircraftType, Fuel,
DepDate, ArrDate, FlightTime,
Remarks, Server
)
VALUES (
?, ?, ?, ?,
?, ?, ?,
?, ?, ?,
?, ?
)
';
// This is just an example - don't forget to check for errors
$sth = mysqli_prepare($mydb, $PiRepSubmissionSqlQuery);
mysqli_stmt_bind_param(
$sth,
'iiiisssssiss', // these should correspond to your SQL datatypes
$PID, $FLID, $DEPID, $ARRID,
$FlightPlan, $AircraftType, $Fuel,
$DepDate, $ArrDate, $FlightTime,
$Remarks, $Server
);
mysqli_stmt_execute($sth);

You should use mysql function TIMESTAMPDIFF to get difference between dates. So your query should look like this:
$PiRepSubmissionSqlQuery = "INSERT INTO Pireps (PID, FLID, DEPID, ARRID, FlightPlan, AircraftType ,Fuel ,DepDate ,ArrDate, FlightTime ,Remarks ,Server)
VALUES ('$PID', '$FLID', '$DEPID', '$ARRID','$FlightPlan' ,'$AircraftType' ,'$Fuel','$DepDate' ,'$ArrDate' ,TIMESTAMPDIFF(HOUR, ArrDate, DepDate), '$Remarks' ,'$Server')";

Related

mysql query in php now()wrong date, i need help to this script

This is my code :
date_default_timezone_set('Europe/Rome');
$dt2=date("Y-m-d H:i:s");
$query = $connection->prepare("INSERT INTO `sessions` ( `user_id`, `session_key`, `session_address`, `session_useragent`, `session_expires`) VALUES ( ?, ?, ?, ?, DATE_ADD('$dt2',INTERVAL 1 HOUR) )");
Since now() gave me a 5 hour time zone back, I use $dt2 (contains timestamp value of Europe/rome). In DATE_ADD, the first parameter will be the $dt2 instead of now(). I need to retrieve the actual Italian time by doing this code, I have already set the time zone in Italy in php.ini and echo the $dt2 it works perfectly but it fails to pass in query.
What wrong on my code? The format of the date on the database is datetime.

Cannot save value for field type 'interval' with Doctrine for Postgres

I am using Symfony and Doctrine to try and save a DateInterval for a field (called duration) of type interval.
I am getting the following error:
An exception occurred while executing 'INSERT INTO workout_sessions (id, location, start_time, end_time, duration, created_at, updated_at, user_id, workout_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [14, \"home\", \"2019-01-23 08:27:00\", \"2019-01-23 09:45:00\", \"-P00Y00M00DT01H18M00S\", \"2019-01-23 09:04:41\", null, 10, 8]:\n\nSQLSTATE[22007]: Invalid datetime format: 7 ERROR: invalid input syntax for type interval: \"-P00Y00M00DT01H18M00S\""
My code is as follows:
public function setDuration(): self
{
if ($this->endTime) {
$interval = $this->endTime->diff($this->startTime);
$this->duration = $interval;
}
return $this;
}
In the above, endTime and startTime are both PHP DateTime objects.
The problem is that when Doctrine converts the DateInterval (created by the $this->endTime->diff($this->startTime)) it prepends the Postgres interval with a + or a -.
When I remove the plus or minus from the start of the string and add the value manually, it works. However, when I leave it on, Postgres will not accept the value.
Does anyone know a way to tell Doctrine to remove the prepended symbol?
Edit
The version of Dbal I am using is 2.5

php mysqli repeated fields in prepared statement

I need to convert an existing project from mysql to mysqli and using prepared statement.
In the existing project there are queries that uses repeated variable values.
One such example is this: where the $prev_yr is used 3 times.
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '$prev_cl', '$prev_yr', '$prev_lvl', '', '123456789', '$prev_yr-01-01', '$prev_yr-12-31' from student Where StudentID in ($ids) ";
Is there a better method than this:
$sqlins = "Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)
select StudentID, '?', '?', '?', '', '123456789', '?-01-01', '?-12-31' from student Where StudentID in (?) ";
$stmt = $mysqli->prepare($sqlins);
$stmt->bind_param("ssssss", $prev_cl,$prev_yr,$prev_lvl,$prev_yr,$prev_yr,$ids);
$stmt->execute();
I am wondering if there is a way of binding the $prev_yr once for all 3 occurrences.
Because there are other queries that may have 2 occurrences of $prev_lvl, 5 occurrences of $prev_yr etc in one statement. The idea is that when the repeated occurrences of multiple variables becomes many in a statement - it becomes quite confusing to arrange them in the bind_param.
Any solution?
Thank you.
Does it even work like that, typical you wont't do this '?-01-01' in a query. I haven't used Mysqli, in about 4 years, as all I use now a days is PDO. But as far as I know when you send that to prepare it's gonna puke on the ? being in a string.
I would split it, there actually is no real need to do the select because the only thing being selected is the studentID which you already have. Simply
$insert = $mysqli->prepare("Insert into studentclass (`StudentID`, `ClassID`, `Year`, `Level`, `SNo`, `TermList`, `DateStart`, `DateEnd`)VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
foreach( $ids AS $id ){
$stmt->bind_param("issssiss", $id, $prev_cl,$prev_yr,$prev_lvl,'', '123456789', $prev_yr.'-01-01',$prev_yr.'-12-31');
$stmt->execute();
}
I can't test it so hopefully I got everything in the right place.
As I said I don't think you can bind to the Fields part of the query and certainly not inside a partial string, besides it's making a select that is un-needed. Just make sure to prepare the insert before the loop.
Just to clearly the only thing that select actually gets from the DB is this
select StudentID ... from student Where StudentID in (?)
The rest are added in as "fake" columns, I don't know the term for it. It's difficult to read the original query..
I am wondering if there is a way of binding the $prev_yr once for all 3 occurrences.
No.
Besides, it wouldn't work this way anyway, as you cannot bind just an arbitrary query part of your choice. You can bind a complete data literal only. Means instead of '?-01-01' it should be just ?, whereas in your PHP code you should make it
$dateStart = "$prev_yr-01-01";
and then bind this variable for the whole value. So there will be no more repeating variables.

Comparing A Time Value Against Database To Stop Repeat Entries

I am inserting values into a database.
If the time the values were created is less than 24 hours then I insert like this,
$stmt = $con->prepare('
INSERT INTO taggedPlaces
(id, created_time, place_id, city, country, latitude, longitude, state, street, zip, name)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
');
foreach($graphObject['tagged_places']->data as $data) {
if (time() - strtotime($data->created_time) < 86400) {
$stmt->execute(array(
$data->id,
$data->created_time,
$data->place->id,
$data->place->location->city,
$data->place->location->country,
$data->place->location->latitude,
$data->place->location->longitude,
$data->place->location->state,
$data->place->location->street,
$data->place->location->zip,
$data->place->name
));
}
}
Everytime I return to the page it takes the same entries and continuously adds them to the database.
I would like to say something like
if $data->created_time == any created_time value in the DB then don't add this value,
as well as currently I am doing
if (time() - strtotime($data->created_time) < 86400)
to make sure it is not older then 24 hours.
How can I add this condition?
Option 1: (Recommeded)
Make id the primary key for your table, taggedPlaces:
ALTER TABLE taggedPlaces ADD PRIMARY KEY(id)
Then change your insert statement to use INSERT IGNORE which will skip duplicate inserts.
Option 2:
Make created_time a unique field in taggedPlaces:
ALTER TABLE taggedPlaces ADD UNIQUE(created_time);
Then, again, use INSERT IGNORE to skip duplicates.
Option 3: (Not recommeded, but will work)
Prior to running your insert, perform another query to check if $data->created_time is already in the table:
$check = $con->prepare('
SELECT id FROM taggedPlaces
WHERE created_time = ?
');
$check->execute(array($data->created_time));
if (count($check->fetchAll()) == 0) {
// No duplicates found. Proceed...
}

Incorrect datetime value: '31-01-2013' for column 'user_date' at row 1

$query_insert = "INSERT INTO users (user_name, user_pass, user_email, user_date, user_level, user_posts)
VALUES(?,?,?,?,?,?)";
$insert = $mysqli->prepare($query_insert);
$insert->bind_param("ssssii", $username, $password_enc, $email, $date, $level_start, $post_start);
$insert->execute();
$date = date('d-m-Y');
Those are the related parts. The only thing is...when i execute this it doesnt add to the table
I had a look around and someone said to have $insert->error; so I put that in and this came up
Incorrect datetime value: '31-01-2013' for column 'user_date' at row 1
Anybody able to help?
It has to be 2013-01-31, i.e. date('Y-m-d')
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html
when inserting value on date data type, it should be on the following format yyyy-MM-dd, so in your example date, it should 2013-01-31.
Don't worry about the pattern of dates when saved on the database. Leave it as is. If you are concern about the formatting, then you can do it during your projection of the data by using such function called DATE_FORMAT.
DATE_FORMAT()

Categories