show data only if currentmonth and currentyear are larger than - php

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 .

Related

Compare date to today does not work

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";

time period in time period (PHP)

i try to find out if a Timeperiod is inside a timeperiod. I have my reference time period and my comparative time period.
Let me make an example:
Time period A (reference) goes from 1.1.2014 to 1.2.2014 (tt.mm.yyyy).
Time period B (comparative) goes from 1.4.2014 to 1.5.2014.
=> This would be totaly ok.
Time period C (reference) goes from 1.1.2014 to 1.3.2014
Time period D (comparative) goes from 1.2.2014 to 1.5.2014.
=> Not ok because D is in C.
I hope you get what i want. I tried to make serval < = > if actions but this starts to get to huge and slow. Maybe there is a faster ways to do so.
Also, is MySQL able to do such things?
you can try this with php timestamp
$reference_start_date = "1.1.2014";
$reference_end_date = "1.2.2014";
$comparative_start_date = "1.4.2014";
$comparative_end_date = "1.5.2014 ";
$reference_start_time = strtotime(str_replace(".", "-", $reference_start_date);
$reference_end_time = strtotime(str_replace(".", "-", $reference_end_date);
$comparative_start_time = strtotime(str_replace(".", "-", $comparative_start_date);
$comparative_end_time = strtotime(str_replace(".", "-", $comparative_end_date);
if($comparative_start_time>$reference_start_time && $comparative_start_time<$reference_end_time)
{
echo "Not OK";
}
else if($comparative_end_time>$reference_start_time && $comparative_end_time<$reference_end_time)
{
echo "Not OK";
}
else if($comparative_start_time<$reference_start_time && $comparative_end_time>$reference_end_time)
{
echo "Not OK";
}
else
{
echo "OK";
}
you can do like below:
Check Reference_start >= comparative_start && Reference_end < comparative_end, If this condition become true than your time will be overlapped.
If you have a reference period (having startDate and endDate) and you have a comparative period, then you can have this where clause in MySQL:
where ((reference.startDate > comparative.endDate) or reference.endDate < comparative.startDate)
which would be true if the two periods have no intersection.
Assuming you have your dates give in UTC it is really simple to compare two date ranges. There are 5 specific cases that could happen:
11111......
......22222
..11111.....
.....22222..
...11111....
...22222....
.....11111..
..22222.....
......11111
22222......
Only the first and the last one are the ones you are looking for. It's easy to construct an if query of it and negate it:
if (!($dateRange1End <= $dateRangeStart2 && $dateRange2End <= $dateRange1Start))
// NOT OKAY
else
// OKAY

PHP Integers with leading zeros

Particularly, 08 and 09 have caused me some major trouble. Is this a PHP bug?
Explanation:
I have a calendar 'widget' on a couple of our client's sites, where we have a HTML hard-coded calendar (I know a PHP function can generate n number of months, but the boss man said 'no').
Within each day, there is a PHP function to check for events on that day, passing the current day of the month like so:
<td valign="top">01<?php printShowLink(01, $events) ?></td>
$events is an array of all events on that month, and the function checks if an event is on that day:
function printShowLink($dayOfMonth, $eventsArray) {
$show = array();
$printedEvent = array();
$daysWithEvents = array();
foreach($eventsArray as $event) {
if($dayOfMonth == $event['day'] && !in_array($event['id'], $printedEvent)){
if(in_array($event['day'], $daysWithEvents)) {
echo '<hr class="calendarLine" />';
} else {
echo '<br />';
}
$daysWithEvents[] = $event['day']; // string parsed from timestamp
if($event['linked'] != 1) {
echo '<div class="center cal_event '.$event['class'].'" id="center"><span title="'.$event['title'].'" style="color:#666666;">'.$event['shorttitle'].'</span></div>';
$printedEvent[] = $event['id'];
} else {
echo '<div class="center cal_event '.$event['class'].'" id="center">'.$event['shorttitle'].'</div>';
$printedEvent[] = $event['id'];
}
}
}
}
On the 8th and 9th, no events will show up. Passing a string of the day instead of a zero-padded integer causes the same problem.
The solution is as what is should have been in the first place, a non-padded integer. However, my question is, have you seen this odd behavior with 08 and/or 09?
I googled this and couldn't find anything out there.
Quote it. 0123 without quotes is octal in PHP. It's in the docs
$ php -r 'echo 01234, "\n01234\n";'
668
01234
$
So you should change your code to
<td valign="top">01<?php printShowLink('01', $events) ?></td>
It's been a while since I've had to wade through so much PHP been doing mostly Javascript for 3 years. But 08 and 09 being a problem makes me think: they could be getting treated as octal (base 8), and the digits 8 and 9 do not exist in octal.

preg_match for mysql date format

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.

Outputting the name of the month instead of the number

I have a query which returns 3 fields, one of which is the month as a two digit number.
I want to basically have it so if month == 1 output january, if month == 02 output febuary etc
This is what I am trying, but this does not work at all, and prevent the entire column from being displayed in PHP.
while ($row = mysql_fetch_array($sqlstr)) {
if ($row['theMonth']=="6") {
echo "<td>{June}</td>";}
echo "<td>{$row['sumSales']}</td>";
echo "<td>{$row['sumPurchases']}</td>";
echo "</tr>";
}
}
What is the correct way to do what I want, and why is what I am doing wrong?
The SQL query I am using is:
SELECT theMonth, sum(Sales) as sumSales, sum(Purchases) as sumPurchases
FROM
( SELECT date_format(saledate, '%Y-%m') AS theMonth, sales.cost as Sales, 0 AS Purchases
FROM sales, products
WHERE sales.product=products.name AND category='Food' OR category='Bocas'
OR category='Bebidas' OR category='Flor de cana por botellas'
OR category='Vino por botella' OR category='hora feliz'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth, 0 as Sales, purchases.cost as Purchases
FROM purchases
) AS all_costs
group by theMonth
I donĀ“t think I could just replace
SELECT date_format(purchasedate, '%Y-%m') AS theMonth
with
SELECT MONTHNAME(purchasedate) AS theMonth
So what would be the best way to return the month name as text in SQL?
In your SQL you can use DATE_FORMAT to convert a date to a month name:
SELECT DATE_FORMAT(NOW(), '%M')
July
The list of allowable specifiers can be found in the MySQL documentation.
(MONTHNAME should also work too.)
The reason why your current method doesn't work is because you are currently outputting both the year and the month (e.g. "2010-06") and this string doesn't compare equal to the string "6".
.
function month_name($int) {
return date( 'F' , mktime(1, 1, 1, (int)$int, 1) );
}
echo month_name(2); // February
First option would be to modify your SQL query to return the month as a name rather than (or as well as) a numeric. See MONTHNAME
Second option would be to use PHP's date functions to generate the name for you
$monthName = date('F',mktime(1,1,1,$row['theMonth'],1,2010));
Third would be to use a monthnames array, similar to zebediah's suggestion
There is probably a php builtin for that, but not using anything like that
$monthNames = array(1 => "January", 2 => "Febuary", 3 => "March", .... 12 => "December");
while ($row = mysql_fetch_array($sqlstr)) {
echo "<td>{$monthNames[$row['theMonth']]}</td>";
echo "<td>{$row['sumSales']}</td>";
echo "<td>{$row['sumPurchases']}</td>";
echo "</tr>";
}
You've got a closing curly brace at the end of the line on your first echo statement. That's causing PHP to prematurely terminate the conditional block, then it has a parse error when it stumbles across your last closing curly brace since it doesn't have an opening match.
You can get the name of the month from a timestamp (if you have one) with the date function. date('F', $timestamp); see the php date function reference
Doing it in the SQL statement is probably your easiest and most performance-friendly way of handling this particular situation.

Categories