I want to display a text if the date in the database matches today's date.
$userdate = date("m/d/Y", strtotime($rr['last_login']));
$today = date("m/d/Y");
if ($userdate==$today){
echo "<test>";
}
Even if it is today's date, the records never echo out the string.
Interestingly, if I change it to
if ($userdate!=$today){
it also does not display the <test>.
My bad! I was not trying to echo out any html thing. The < brackets were just random characters. I changed it to "test" and now it works. Sorry for the < > characters causing confusion!
Since this is PHP, one would assume you're looking at the result in a browser, which will interpret the "<test>" as an HTML tag, and thus it will ignore it. Try changing the "echo" to simply echo "test<br>";
Also, if you are always dealing with a database, you could also use this:
if (substr($rr['last_login'], 0, 10) == date('Y-m-d'))
echo "test<br />\n";
Related
I need to check if entered date is between 2019-09-01 - 2019-12-31
I can do this as follows: $koodi is user input
$pattern1 = "/^2019-(09|11)-([0-2][0-9]|30)$/";
$pattern2 = "/^2019-(10|12)-([0-2][0-9]|3[0-1])$/";
if(preg_match($pattern1, $koodi) || preg_match($pattern2, $koodi)) {
echo "<code>$koodi</code> ok!<br>\n";
}
else {
echo ("<code>$koodi</code> NOT ok!<br>\n");
}
I was trying to make those two conditions into single regex statement, is that possible and if so how?
I tried:
$pattern = "/^2019-(09|11)-([0-2][0-9]|30)$ | ^2019-(10|12)-([0-2][0-9]|3[0-1])$/";
Did not work, neither the following where i tried to put parentheses around conditions:
$pattern = "/(^2019-(09|11)-([0-2][0-9]|30)$) | (^2019-(10|12)-([0-2][0-9]|3[0-1])$)/";
Please don't use a regex to do that, what if the dates change or what if the next developer has to come and work on this and figure out what your doing?
According to this article you can check if a date is between 2 dates by doing something like this.
<?php
$currentDate = date('Y-m-d');
$currentDate = date('Y-m-d', strtotime($currentDate));
$startDate = date('Y-m-d', strtotime("01/09/2019"));
$endDate = date('Y-m-d', strtotime("01/10/2019"));
if (($currentDate >= $startDate) && ($currentDate <= $endDate)){
echo "Current date is between two dates";
}else{
echo "Current date is not between two dates";
}
as for why your patterns didn't work its because you have a space around the pipe in the middle and you may possibly need to wrap the whole thing in brackets. You also have the $ half way through the regex which is matching the whole string, I would usually only have it at the end, like this: -
^(regex1|regex2)$
I haven't written the correct version in case your tempted to use it, (please use the date objects method)
Let say currentmonth is 06 and currentyear 2017
i have dropdown of year and month ..
if i select year 2017 and month of July which is larger then currentmonth
how do i show there is not data available yet
my current code..and its not working..i'm a newbie and not sure im doing this right or not...
$mystartingyear=2017;
$mystartingmonth=01;
$currentmonth=date("m");
$currentyear=date("Y");
if ($currentyear >= $mystartingyear && $currentmonth >= $mystartingmonth)
{
echo "Show Data";
}
else
{
echo "No Data yet";
}
i also tried it like this
$mystartingyear=2017;
$mystartingmonth='01';
$currentmonth=12;
$currentyear=2017;
//$currentmonth=date("m");
//$currentyear=date("Y");
if ($currentyear >= $mystartingyear && $currentmonth >= $mystartingmonth)
{
echo "Show Data";
}
else
{
echo "No Data yet";
}
it always display "show data"
Edit:
Integers from 01 to 07 are ok just as long as you don't do 010 (with 3 integers) since that will be represented as 8. But as soon as you start hitting 08 and 09 for the months of August and September (which may be what's in your unknown dropdown), you will have problems.
So it's best you quote it.
Consult "Footnotes".
Original answer:
The leading zero in 01 for:
$mystartingmonth = 01;
^^
is treated as an octal.
It needs to be quoted:
$mystartingmonth = '01';
Octals references:
http://php.net/manual/en/language.types.integer.php
https://en.wikipedia.org/wiki/Octal
Footnotes:
If your current code is failing you, then something else is failing you.
You mention in your question that you're using this from a dropdown and that code wasn't included, nor how it's being passed.
Use PHP's error reporting, set to catch and display:
http://php.net/manual/en/function.error-reporting.php
Verify your conditional statement's logic also; both conditions must be met.
There is missing semicolon after first echo i.e. code should be
echo "Show Data";
Then every thing should work fine,
The date(); function in php returns the date in string and when you compare a string with integer it is implicitly converted into equivalent integer variable,if you want for sure you can use intvar(); function which converts variable to equivalent integer.But in your case it is not necessary.For more about i recommend you to read php manual .
I am creating a calendar function in php. Along with the function I need a "previous" and "next" link that show the previous or next month using the GET method. The links don't work the way I expect them to. From what I've found through debugging it doesn't look like it's actually adding or subtracting 1 from month.
This is currently what I have:
$month=$_GET["month"];//should initially set them to null?
$year=$_GET["year"];
//previous and next links
echo "<a href='calendar.php?month=<?php echo ($month-1)?>'>Previous</a>";
echo "<a href='calendar.php?month=<?php echo ($month+1)?>'>Next</a>";
//Calls calendar method that returns the calendar in a string
$calDisplay=calendar($month,$year);
echo $calDisplay;
PHP doesn't do calculations inside strings and doesn't parse PHP tags inside strings. You are already in 'PHP mode', and opening another PHP tag inside the string just outputs that tag as you may have noticed when you inspected the link in your browser.
Instead, try closing the string, concatenating the next/previous month (using the dot operator), and concatenating the last part of the link:
//previous and next links
echo "<a href='calendar.php?month=" . ($month-1) . "'>Previous</a>";
echo "<a href='calendar.php?month=" . ($month+1) . "'>Next</a>";
You can also calculate the values into variables first, because simple variables can be used inside double-quoted strings:
//previous and next links
$previousMonth = $month-1;
$nextMonth = $month+1;
echo "<a href='calendar.php?month=$previousMonth'>Previous</a>";
echo "<a href='calendar.php?month=$nextMonth'>Next</a>";
On the first request, you may not have a month at all, so you may want to check for that too, for instance using isset.
$month = 1;
if (isset($_GET['month'])) {
$month = (int)$_GET['month'];
}
As you can see, I already did an (int) typecast there too. Combining this with the variables version, allows you to make the code a little more solid by performing some checks on the input, and only output the previous/next links if they make sense.
$month = 1;
if (isset($_GET['month'])) {
$month = (int)$_GET['month'];
}
if ($month < 1 || $month > 12) {
// Invalid month. You can choose to throw an exception, or just
// ignore it and use a default, like this;
$month = 1;
}
//previous and next links, if necessary.
$previousMonth = $month-1;
$nextMonth = $month+1;
if ($previousMonth >= 0) {
echo "<a href='calendar.php?month=$previousMonth'>Previous</a>";
}
if ($nextMonth <= 12) {
echo "<a href='calendar.php?month=$nextMonth'>Next</a>";
}
Oh, and a minor detail. Personally I don't like to put 'big' chunks of HTML inside a string, so I'd rather use some template, or at least write it like this. As you can see, you can close and open PHP tags (just not inside strings), so you can output plain HTML from within your PHP code. The <?= $x ?> notation is a shorthand for <? echo $x; ?>.
//previous and next links, if necessary.
$previousMonth = $month-1;
$nextMonth = $month+1;
if ($previousMonth >= 0) {?>
<a href='calendar.php?month=<?=$previousMonth?>'>Previous</a>
<?php}
if ($nextMonth <= 12) {?>
<a href='calendar.php?month=<?=$nextMonth?>'>Next</a>
<?}
Try doing something like the following:
echo sprintf('Previous', http_build_query(array('month' => $month - 1)));
echo sprintf('Next', http_build_query(array('month' => $month + 1)));
While it seems more convoluted, it serves two purposes.
Its cleaner and less messing around with string concatination
You get to learn about sprintf and http_build_query functions which can be very useful in certain situations. sprintf is a string formatting function which basically takes a string as its first parameter and substitutes certain tokens with the next n parameters. In this example, %s is a token which means replace it with a string, which is passed as the second function. http_build_query takes an associative array and builds a http query from it. So in the code above, the http_build_query function will return month=11 (assuming the month was 12) for the Previous link. You can also add multiple array parameters and it will build the query string with the ampersands.
While the other answers do what you need, its always wise to look at and understand other PHP functions.
The $_SERVER REQUEST METHOD when you click on a link is 'GET'.
use the parse_str function and place your $_GET keys and variables into an array.
parse_str($_SERVER['QUERY_STRING'],$output);
print_r($output);
Maybe you can test for that. Is this what you are looking for?
Since everything you send via request is considered a String, try this casting integer.
HTML
<!-- previous and next links -->
<a href='calendar.php?month=<?php echo ((int)$month - 1)?>'>Previous</a>
<a href='calendar.php?month=<?php echo ((int)$month + 1)?>'>Next</a>
I am in the middle of setting up a basic CMS that allows the client to add articles to their mobile app. The CMS is coded in PHP and will use JSON to deliver the content to the mobile app.
Now my problem is there is an option to publish the article at a certain date, so I want to validate the date to check it is valid.
So to test possibilites I made a small script. I am using strtotime() to check the date is valid, my script is:
<?php
$date[] = '2011-31-01';
$date[] = '2011-02-31';
foreach($date as $str) {
if(strtotime($str) == false) {
$result[] = '<p>[' . $str . '] Resulted in an <span style="color: red;">Error.</span></p>';
} else {
$result[] = '<p>[' . $str . '] Resulted in <span style="color: green;">Success.</span></p>';
}
}
foreach($result as $return) {
echo $return;
}
?>
Now my problem is the date 2011-02-31 which is 31st February 2011 is returning as valid, when obviously it isn't. So my question is why does it do this? and is there a better method to check that the date is valid and exists?
Thanks in advance.
checkdate(); Validates a Gregorian date. Returns TRUE if the date given is valid; otherwise returns FALSE.
if(checkdate(2, 31, 2011)){
echo "Yeah";
} else {echo "nah";}
It returns false!
That's the way to go.
Unless you have one (or a small set) fixed format for your date string it will be hard to get an acceptable result. In case you know the format, you can either parse the string directly yourself (and test it afterwards with checkdate), or you use strptime to try parsing against known formats until you get a valid result.
If you don’t know the format, and you have to use strtotime, then you are required to accept that strtotime will try parsing the date string in the best possible way. This may lead to different dates than it was expected to be.
im trying to validate a date to see if it matchs the mysql format
this is the code
$match = "/^\d{4}-\d{2}-\d{2} [0-2][0-3]:[0-5][0-9]:[0-5][0-9]$/";
$s = $this->input->post("report_start"). " " . $this->input->post("report_start_time").":00";
$e = $this->input->post("report_end"). " " . $this->input->post("report_end_time").":59";
if($this->input->post("action") != "")
{
echo trim($s). " => " . preg_match($match, trim($s));
echo "<br>";
echo trim($e). " => " . preg_match($match, trim($e));
}
the date format goes into $s and $e are
$s = 2011-03-01 00:00:00
$e = 2011-03-01 23:59:59
and they both return false (0).
i tested the pattern on http://www.spaweditor.com/scripts/regex/index.php and it returns true (1)
http://pastebin.com/pFZSKYpj
however if i manual inter the date strings into preg_match like
preg_match($match, "2011-03-01 00:00:00")
it works.
i have no idea what im doing wrong
======================
now that i think about it, i only need to validate the houre:min part of the datetime string.
im manually adding the seconds and the date is forced by a datepicker and users cant edit it
You're making your work harder that it needs to be. In php there are many date handling functions that mean you don't have to treat dates like strings. So, rather than test that your input dates are in the correct format, just insist on the correct format:
$adate= date_create('January 6, 1983 1:30pm'); //date format that you don't want
$mysqldate= $adate->format("Y-m-d h:i:s");//date format that you do want
There are also functions to check that a date is a real date, like checkdate.
ok heres wat i did.
since im forcing the date format and the ending seconds of the time part
i just validated the hour:mini part using "/^2[0-3]|[01][0-9]:[0-5][0-9]$";
and if that returns true i put everything together end reconstructed the final datetime string
$match = "/^2[0-3]|[01][0-9]:[0-5][0-9]$/";
$s_d = $this->input->post("report_start");
$s_t = $this->input->post("report_start_time");
$e_d = $this->input->post("report_end");
$e_t = $this->input->post("report_end_time");
if($this->input->post("action") != "")
{
if(
( preg_match($match , trim($s_d." ".$s_t.":00")) )
&& ( preg_match($match , trim($e_d." ".$e_t.":59")) )
)
{
$r = $this->model_report->client_hours_logged(array($s,$e));
$data['report'] = $r;
var_dump($r);
//$this->load->view("report/client_hours_per_client",$data);
}
}
Watch out:
[0-2][0-3] is not a good regex for hour values - it will match 01, 12, 23 and others, but it will fail 04 through 09 and 14 through 19.
Better use (2[0-3]|[01][0-9]) instead.
I use this to validate a 'Y-m-d H:i:s' format date string:
match = '/^[12][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[01]) ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/';
You could use strtotime and date to parse and format the date properly.
Why not just simply force the date into the format you want:
$e = '2011-03-01 00:00:00';
$mysqlFormat = date('Y-m-d H:i:s', strtotime($e));
Also, there is a bit of an error in your regex [0-2][0-3]:[0-5][0-9]:[0-5][0-9] will only match the hours of 00,01,02,03,10,11,12,13,20,21,22,23 so it will never match 4am, or 3pm among others. That aside I looked over your RegEx and I don't see any problems with it matching the test cases you've offered. I would check to make sure there is not extra whitespace on either side of date string with trim().
I concur with Tim : MySQL behaves in quirks mode and always tries to go easy on DATE and DATE_TIME column types. You can omit certain parts of your input and it still will try to compensate and achieve that goal successfully to some degree... That's why, most numbers your Reg-ex considers as invalid, MySQL will accept as valid.