I am selecting three columns from my database with
$sql = "SELECT lnumber,violation,datetime FROM violators WHERE lnumber='".$lnumber."'";
and parsing the result into JSONArray and I am getting this result
{"lnumber":"2","violation":"Beating the red light","datetime":"2017-10-15 13:02:34"}
Now what I want to do is how can I parse the "datetime" field without the seconds?
Here is the full code:
$sql = "SELECT lnumber,violation,datetime FROM violators WHERE lnumber='".$lnumber."'";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($lnumber, $violation, $datetime);
while($stmt->fetch())
{
$temp = [
'lnumber'=>$lnumber,
'violation'=>$violation,
'datetime'=>$datetime
];
array_push($result, $temp);
}
echo json_encode($result);
SELECT DATE_FORMAT("2017-10-15 13:52:35", "%Y-%m-%d %H:%i")
Use %H for 2 digit 24 hour format (e.g. 08) or %k for 1 digit.
Reference:
https://www.w3schools.com/sql/func_mysql_date_format.asp
Try it here:
https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_date_format
SELECT DATE_FORMAT("2017-10-15 13:02:34", "%Y-%m-%d %h:%m");
=> 2017-10-15 01:10
MySQL DATE_FORMAT https://www.w3schools.com/sql/func_mysql_date_format.asp
This is if you want to get rid of the seconds during the data fetch.
Related
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);
I need some help with a project I'm working on.
There's a table with 2 dates: date1 and date2 (easier)
Now I need to show all rows where the current date is between date1 and date2.
What I have so far is:
$date = date(Y-m-d);
$sql = 'SELECT * FROM boekingen WHERE "$date" BETWEEN date1 AND date2';
but this doesn't work. Although if I replace "$date" with 2017-01-06 it does work. Now how do I solve this problem?
Thanks in advance!
You need to put quotes around the argument to date():
$date = date('Y-m-d');
And you need to wrap the string you assign to $sql in double quotes, otherwise the $date variable won't be expanded.
$sql = "SELECT * FROM boekingen WHERE '$date' BETWEEN date1 AND date2";
What is the difference between single-quoted and double-quoted strings in PHP?
The manual on date() is clear as to its syntax and using quotes around the arguments.
http://php.net/manual/en/function.date.php
Since yours has none, PHP is assuming you have them pre-defined as constants.
Error reporting would have thrown you the following:
Notice: Use of undefined constant Y - assumed 'Y' in /path/to/file.php on line x
Notice: Use of undefined constant m - assumed 'm' in /path/to/file.php on line x
Notice: Use of undefined constant d - assumed 'd' in /path/to/file.php on line x
Examples taken from Example #4 date() Formatting from the manual:
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>
Use something like this
$date = date(Y-m-d);
$sql = 'SELECT * FROM boekingen WHERE STR_TO_DATE(\'$date'\', \'%m/%d/%Y\') BETWEEN date1 AND date2';
Make sure that date2 is greater than date1.
date = date(Y-m-d);
$sql = 'SELECT * FROM boekingen WHERE "$date"
That is the code on your question.
Using a single quote for string in php will not expand the variable.
Either use double quotes and single quotes around $date or concatenate eg
$sql = 'SELECT * FROM boekingen WHERE "' . $date .'"
Or sprintf
$sql = sprintf('SELECT * FROM boekingen WHERE "%s", $date)
I am looping through a bunch of tables which include the Columns Date, Week and Day. Several rows have the same Week Number for multiple Dates e.g. the dates 2015-12-24, 2015-12-23, 2015-12-22, 2015-12-21 are all 'Week' 52.
I want to add the day of week e.g. 1 through to 5 to the 'Day' Column for 'Week' e.g. 52. Below is my code so far, I do not know what to do while inside each table to achieve the above result.
$sql = "SHOW TABLES FROM $db";
$res = mysql_query($sql);
if (!$res) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
//Update Day in the Tables
$sql1 = "SELECT * FROM $row[0]";
$res1 = mysql_query($sql1);
while(($rs=mysql_fetch_assoc($res1))!=null)
{
//What do I put here?!
}
}
You should use the update statement instead of a loop
UPDATE
"your_table"
SET
"your_table"."Day"=weekday("your_table"."Date")
WHERE
"your_table"."Week"=52
I need to find max date from a table(mysql database). I am storing my date as varchar.
select max(completion_date) from table_name returns wrong value.
http://sqlfiddle.com/#!9/c88f6/3
Assuming the date time format you have in your fiddle (e.g. '12/19/2012 05:30 PM') then:
select max(STR_TO_DATE(completion_date, '%m/%d/%Y %l:%i %p')) from test;
http://sqlfiddle.com/#!9/c88f6/15
It's unclear if you want to factor the time into your rankings or just the date. This example accounts for time too, but you can remove that part of the formatter if desired.
I am not sure why you would want to keep it as varchar not date.
But this will work for varchar:
SELECT completion_date
FROM test
ORDER BY STR_TO_DATE(completion_date, '%m/%d/%Y') DESC LIMIT 1;
http://sqlfiddle.com/#!9/c88f6/10
<?php
// Store dates
$dates = array();
// Loop through and transfer the result set
foreach ($result as $row => $data) {
$dates[$row] = $data['date'];
}
// Sort the array
usort( $dates, "date_sort_function" );
// Max is last date in array.
foreach ($dates as $date) {
$max = $date;
}
?>
Well, something like that. It is a php script and all you have to provide is the sorting function which returns 0 if equal, 1 if older, and -1 if earlier.
I cant seem to figure out a way to format a string in perl to use in a MySQL DateTime() field.
my $time = "Sat Jun 29 11:20:28 2013 -0400"
and i need to format time so it can be entered into a MySQL DateTime() field
Format: YYYY-MM-DD HH:MM:SS
i plan to enter this using perl mysql module
$createQuery = "INSERT INTO something (dated) Values(?) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
You don't have to do any formatting yourself.
$time = time;
$createQuery = "INSERT INTO something (dated) Values( FROM_UNIXTIME( ? )) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
If you do really need a string and your data source is not a unix timestamp, just use any of the formats that MySQL understands.
$time = '2013-06-29 18:50:00';
$createQuery = "INSERT INTO something (dated) Values( FROM_UNIXTIME( ? )) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
You can use the core module Time::Piece which has been part of the Perl core since 5.9 : corelist .
use Time::Piece;
my $time = q(Sat Jun 29 11:20:39 2013 -0400);
my $t = Time::Piece->strptime($time, '%a %b %d %H:%M:%S %Y %z');
print $t->strftime("%Y-%m-%d %H:%M:%S\n");
If you don't have perl 5.9, Date::Manip will sort you:
$date_as_mysql_likes = UnixDate(ParseDate($your_date_here), '%Y-%m-%d %H:%M:%S');