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)
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 have a table named leaves.
----------
id FromDate ToDate
1 20-01-2019 22-01-2019
2 15-01-2019 22-01-2019
3 13-01-2019 20-01-2019
I want all dates between each column.
Can anyone help?
If you want to do it in your php code then you can do it by finding day count between two days and loop it to get the all dates between that two dates.
<?php
$date1 = "2019-01-13";
$date2 = "2019-01-20";
$date1 = strtotime("2019-01-13");
$date2 = strtotime("2019-01-20");
$datediff = $date2 - $date1;
$days = round($datediff / (60 * 60 * 24));
for($i=1;$i<=$days;$i++){
echo $date1 = date('d-m-Y', strtotime($date1 . ' +1 day'));echo ' <br> ';
}
You can try below using datediff() function
select id, fromdate, todate,datediff(ToDate,fromdate) as days
from tablename
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.
i have a report which runs weekly on a friday doing some db queries where data is from monday to friday and producing a table with the results. I am having a problem when the report runs on a friday where the monday is last month. So for example last friday. Friday was the first of august, and the monday was the 28th of july. The below is the date and time portion of my script.
my $date = `date +%Y%m%d`;
chomp($date);
my $time = `date +%H%M%S`;
chomp($time);
my $day = `date +%A`;
chomp($day);
my $time = `date +%H%M%S`;
chomp($time);
my $dispTime = `date +%H:%M`;
chomp($dispTime);
# Set the Dates
my $end = $date;
my $start = $end;
# Check the day and define start and end dates.
if ($day eq "Friday") {
$start = $end - 5;
my #mytime=localtime;
my ($s, $min, $h, $d, $m, $y) = (0, 0, 0, $mytime[3], $mytime[4], $mytime[5]);
my $todayminus5 = strftime "%Y%m%d", $s, $min, $h, $d - 5, $m, $y;
$start = $todayminus5;
In my report logs it prints the date that was calculated and it printed this
Start Date = 2014080,
End Date = 20140801
Does anybody know why this doesnt seem to be able to calculate the date if its over two months?
You should use Time::Piece in conjunction with its sister module Time::Seconds. If you have a reasonably recent version of Perl then it should already be installed as it has been a core module since version 10 of Perl 5.
By the way, you need to subtract four days to get from Friday to the previous Monday!
use strict;
use warnings;
use Time::Piece;
use Time::Seconds 'ONE_DAY';
my $now = localtime;
if ($now->wdayname eq 'Fri') {
my $monday = ($now - ONE_DAY * 4)->strftime('%Y%m%d');
# etc.
}
I would rework the approach you're taking - you're doing multiple invocations of date which is probably a warning sign in the first place. You've got a whole lot of edge cases - subtracting '5' from your days will get you a negative number if it's early in the month - which will break things - but you'll have similar problems when the year changes.
I won't contradict the previous post, but I'd instead suggest you simplify:
my $ONE_DAY_s = 60 * 60 * 24;
my $now = time();
my $then = $now - 4*$ONE_DAY_s;
my ( $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
$year += 1900;
print "Now: $year $mon $mday\n";
( $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($then);
$year += 1900;
print "Then: $year $mon $mday\n";
(transcribed, rather than pasted so beware typos).
You can use $wday to figure out if it's a friday.
Modules exist to do this as well though - I would be very wary of using repeated invocations of an external command, and then trying to mangle the results.
You can use the Datetime module to get the start date and end date
Example:
use strict;
use warnings;
use DateTime;
my $today_date = DateTime->today(); # Current date (Friday)
my $old_date = $today_date->clone()->subtract(days => 4); # First DoW (Monday)
print $today_date, "\n";
print $old_date, "\n";
Outputs:
2014-08-04T00:00:00
2014-07-31T00:00:00
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');