PHP check mysql row for empty date - php

I have created a new date column and it defaults it to 0000-00-00 and I want to check if it has a valid date or all zeros, but none of these codes seem to work for me and I can't figure out why. I know it sees the date, cause when I echo it, it displayed as zeros. How do I check to see if the date column is 0000-00-00? Here is what I tried and none of them have worked.
if (trim($row['date']) == '' || substr($row['date'],0,10) == '0000-00-00') {
// empty date
}
if (strtotime($row['date']) == '0000-00-00'){
// empty date
}
if ($row['date'] == '0000-00-00'){
// empty date
}
EDIT
Looks like it might just be a problem with my godaddy hosting server, I uploaded the files to a free webhosting and solution 3 is working over there. Sorry to waste everyone's time, I do appreciate the quick responses.

You can check the following condition instead of yours...
There strtotime() return false if that not contains a specific date string or for proper check of empty string you can use empty() function and for check that string contains '0000-00-00' like data then you can use strpos() as like the below code:
if(empty(trim($row['date'])) || (strpos($row['date'], '0000-00-00') !== false) || (!strtotime($row['date'])))
{
// empty date
}

If we aren't sure about how the date is being returned, try using date and strtotime together to ensure correct format:
if (date('Y-m-d', strtotime($row['date'])) > '0000-00-00'){
//Valid
}

Simply use empty() with strtotime will check all the empty cases
<?php
$row['date'] = '0000-00-00';
if(empty(strtotime($row['date']))){
// empty date
}
else{
//not empty date
}
If about your 3 condition it should be like below instead of using if ladder use else if and In 2nd condition your are comparing timestamp integer(strtotime will return int seconds) to the string date('0000-00-00') that is in correct
<?php
$row['date'] = '0000-00-00';
if (trim($row['date']) == '' || substr($row['date'],0,10) == '0000-00-00') {
// empty date
}
else if(strtotime($row['date']) == strtotime('0000-00-00')){
// empty date
}
else if ($row['date'] == '0000-00-00'){
// empty date
}

Related

phpspreadsheet setFormatCode not working

Sometimes I'm unable to format an Excel cell data as date using $date wiht format 'yyyy-mm-dd' (eg. 2017-07-12)
if ($date != '') {
$t_date = PhpOffice\PhpSpreadsheet\Shared\Date::stringToExcel($date);
$sheet->setCellValueByColumnAndRow($column,$row, $t_date);
$sheet->getStyleByColumnAndRow($column,$row)->getNumberFormat()->setFormatCode(PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
}
The previous code fails when a $date is not valid (eg. 0000-00-00), and keeps failing in all sequent applies.
My solution is
if ($date != '') {
$t_date = PhpOffice\PhpSpreadsheet\Shared\Date::stringToExcel($date);
if ($t_date !== false) {
$sheet->setCellValueByColumnAndRow($column,$row, $t_date);
$sheet->getStyleByColumnAndRow($column,$row)->getNumberFormat()->setFormatCode(PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
$sheet->getStyleByColumnAndRow($column,$row)->getFont()->setBold(true);
$sheet->getStyleByColumnAndRow($column,$row)->getFont()->setBold(false);
}
}
Settting and unsetting the bold stile kwwpd working the setFormatCode in moste fo the cases ... I do not know why.

PHP DD/MM/YYYY Validation [duplicate]

This question already has answers here:
My pattern isn't matching a ISO style date, why? [duplicate]
(3 answers)
Closed 7 years ago.
apologies for probably a simple question, but i am new to PHP and Javascript.
I am creating a login validation in PHP that requires a registering user to input their date of birth in a DD/MM/YYYY Format, that returns an error message if the date is entered in any other format. I am unsure how to do this, other than using preg_match, however this doesnt seem to work...
variables:
$DOB = $_POST['DOB'];
$error_message = '';
The Date Validation Segment
elseif (!preg_match("/^(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}$/", $DOB))
{
$error_message = 'Invalid Date';
}
Error Display
if ($error_message != '')
{
echo 'Error: '.$error_message.' Go Back.';
echo '</body> </html>';
exit;
}
else
{
echo'<p><strong>Form Submitted Successfully!</strong></p>';
}
This is not a duplicate, i tried other threads and none of their solutions worked.
You should use more than a regular expression. For example, you should not allow something like 31/02/2015, because there's no 31th in February!
I have a function that works well:
function isDate($string) {
$matches = array();
$pattern = '/^([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})$/';
if (!preg_match($pattern, $string, $matches)) return false;
if (!checkdate($matches[2], $matches[1], $matches[3])) return false;
return true;
}
It first uses preg_match to check for the formal validity of DD/MM/YYYY, grabbing DD, MM and YYYY portions into the $matches array. Then it check the validity of the date itself using the built-in PHP function checkdate.
You can use that in your code like:
if (!isDate($DOB)) {
$error_message = 'Invalid Date';
}
string_explode given string and then pass parts of it to
bool checkdate ( int $month , int $day , int $year )
unfortunately you cannot know if user posted month and day in your format if day is not greater than 12
You can do it like this in PHP:
$date=explode("/",$_POST['DOB']);
if(checkdate ($date[1] ,$date[0] ,$date[2]))
{
echo "valid";
}
else
{
echo "invalid";
}
checkdate will only return true if the three value behind "/" is valid, so if there's no "/" its invalid, same as they put numbers in wrong order.
check manual http://php.net/manual/en/function.checkdate.php

String confusion 1) OR in if cond. and strtolower not lowering

Trying to convert times such as - 215pm or 2:15 am or whatever to a 14:15 or 02:15 type string. (I am NOT using a TIME format for reasons to tedious to go into.)
Have managed to get an array output that contains hours, minutes and am/pm (but only if characters are present).
I want to allow erroneous characters through so I can EXPLICITLY fire an error message but a) I cannot get a "simple" OR test to work and b) strtolower is not working for me - I don't know why.
$hour= $matches['h'];
$minute=$matches['m'];
if(!array_key_exists('ap', $matches)){$matches ['ap'] ="am";};
$ampm=$matches['ap'];
strtolower ($ampm);
debug ($hour,"hr");
debug ($minute,"min");
debug ($ampm,"ampm");
if ($ampm=="am" or $ampm=="pm") {echo "fine";}; // ALWAYS TRUE
if ($ampm==="am" or $ampm==="pm") {echo "fine";}; // FAILS WITH UPPER CASE AM AND PM
if ($hour<12 and $ampm=="pm") {$hour = $hour+12;};
debug ($hour,"hr");
debug ($minute,"min");
debug ($ampm,"ampm");
So I do not understand why the simple string test $ampm=="am" or $ampm=="pm" is always true but that is just academic. But I REALLY do not understand why strtolower does not change "AM" to "am" so that I cannot even use a === congruence test.
Any thoughts?
Simple mistake in your code. Change:
strtolower ($ampm);
To:
$ampm = strtolower ($ampm);
Do this to replace the variable:
$ampm = strtolower($ampm);
Also, $ampm is always true because the condition says
"if it is am, it is true OR if it is pm, it is true"
so what you want to do is:
if(isset($ampm) && $ampm === "am")
{
//its am
} else if(isset($ampm) && $ampm === "pm")
{
//its pm
} else
{
//its neither
}

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 verify correct time format in $value

I have an online form that has a few fields with time data. I store this data into the MySQL data base into a time field, which needs a format hh:mm:ss. If the user inputs the time in this format correctly, then i want to accept the data. I also want to allow users to input the time in standard US time, like 9:30 am or 11:25 pm or 10:27 am etc.
Basically I want to test if the time is in the proper database format first (hh:mm:ss), then if it is not, test if it is in the second accepted format (hh:mm am/pm), and if it is, then I will use the PHP function strtotime() to convert it into the database time format. If it is in neither of these formats, then we display an error message and die.
Does anyone know how to test if the value of a variable matches one of these time formats?
Pseudo PHP code of what I want to do:
<?php
$value = //some time;
if (is_database_time($value)){
// good no problem
}else if (is_usa_time($value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>
** EDIT **
Thanks everyone for the help. I used some of the info here to make a function that works perfectly:
<?php
function filter_time($key,$value){
// this section handles the storage of time data
if (preg_match('/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)){
//do nothing
}else if (preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value)){
$value = date( 'H:i:s', strtotime($value));
}else{
display_error('incorrect time format in '.$key.' field.');
}
return $value;
}
?>
function verify_time_format()
function verify_time_format ($value) {
$pattern1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$pattern2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
return preg_match ($pattern1, $value) || preg_match ($pattern2, $value);
}
Returns TRUE for following values:
2:03:32
02:03:32
23:59:59
15:23 AM
15:23 am
09:41 pm
9:41 PM
etc...
Update:
function filter_time ($key, $value) {
$p1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$p2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
if (preg_match ($p1, $value) || preg_match ($p2, $value))
$res = date ('H:i:s', strtotime ($value));
else
display_error ("incorrect time format in {$key} field.");
return $res;
}
You're already using the strtotime from PHP, and for the values you specified there really is no need to force a specific format.
What you would likely want to test for and ensure, is that the field validates with only digits, the colon, and am or pm as in Wh1T3h4Ck5 answer.
With that in place, your code would likely be similar to the following
<?php
function valid_time($value) {//Wh1T3h4Ck5's function
return preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value);
}
$value = //some time;
if (vald_time($value)){
$time_value = strtotime($value);
echo $time_value;
}else{
die("Error incorrect time format, try again.");
}
?>
Though a more elegant solution would to look into using Jquery/Javascript PRIOR to the form being submitted. You can test and warn the user of improper format before submitting to the PHP script. Leave the validation in the PHP script though as well, with other safeguards if needed.
You can use a regular expression to solve the problem pretty easily. For example:
<?php
$databaseTimePattern = '/^(0[0-9])|(1[0-2]):[0-5][0-9]:[0-5][0-9]$/'; //Matches times in the form hh:mm:ss
$usaTimePattern = '/^([1-9]|(1[0-2])):[0-5][0-9] [a|p]m$/'; //Matches times in the form hh:mm am/pm
$value = //some time;
if (preg_match($databaseTimePattern, $value)){
// good no problem
}else if (preg_match($usaTimePattern, $value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>

Categories