Setup Date Select form php - php

I don't have a background in PHP but a recent client requires some updating so i'm doing my best. What I'm trying to accomplish is first update the form to accept the correct date format to covert using the code I created that will through an error if it's less than 24 hours from the present time. The form now:
<p>
<label for="date">Date:<span>*</span></label>
<span>
<input type="text" name="date" id="date" value="<?php $this->value('date'); ?>" size="25" />
</span>
</p>
<p>
<label for="time">Eat Time:<span>*</span></label>
<span>
<input type="text" name="time" id="time" value="<?php $this->value('time'); ?>" size="10" />
</span>
</p>
<p>
<label for="timedes">AM or PM:<span>*</span></label>
<span>
<select name="timedes" id="timedes">
<option value="0" <?php $this->value('timedes', '0', 'selected="selected"'); ?>>Select..</option>
<option value="AM" <?php $this->value('timedes', 'AM', 'selected="selected"'); ?>>AM</option>
<option value="PM" <?php $this->value('timedes', 'PM', 'selected="selected"'); ?>>PM</option>
</select>
</span>
</p>
The code that I will need to modify to validate if it's less than 24 hours or not.
// define variables for date
date_default_timezone_set('America/New_York'); // timezone
$dateInput = '10/11/2015 15:54'; //date they selected string
$cateringDate = (strtotime("$dateInput")); // date selected converted to time
$dateNow = date('m/d/y H:i'); // current date and time string
$currenttime = (strtotime("$dateNow")); // current date and time converted
$dateAllowed = $currenttime + (86400); // current date and time 24 hours added on
$difference = $dateAllowed - $cateringDate; // date selected vs current date + 24hours
if ($cateringDate >= $dateAllowed) {
echo 'good job';
} else {
echo 'try again';
}

There are multiple ways to do this. But here is one using strtotime:
date_default_timezone_set('America/New_York'); // timezone
$dateInput = '10/11/2015 15:54';
if (strtotime('+24 hours') < strtotime($dateInput)) {
echo 'good job';
} else {
echo 'try again';
}
If strtotime did not understand the format it returns false, so:
if (false === strtotime($dateInput)) {
echo 'Sorry, what?';
}

Use the datetime class and take advantage of the diff method, i.e.:
date_default_timezone_set( 'America/New_York' ); // timezone
$date1 = new DateTime( 'NOW' );
$dateInput = '10/10/2015 15:54';
$date2 = DateTime::createFromFormat( 'm/d/Y H:i', $dateInput );
$diff = $date2->diff( $date1 );
if( $diff->format( '%d' ) != 0 ){
echo "good job";
}else{
echo "try again";
}
We check if the difference (in days) between NOW and the $dateInput is different from 0, zero means less than 24h from a future or previous date.

Related

Validate Date input not empty and not greater than todays date in Php

Help please, am trying to validate a form date input not empty and should not be greater that today's date. this is what I did so far. am getting 000-00-00 inserted in MySQL db. what am I doing wrong?
here is what in the form input
<div class="form-group">
<label>Join Date</label>
<input type="date" name="joindate" class="form-control <?php echo (!empty($joindate_err)) ? 'is-invalid' : ''; ?> " value="<?php echo $joindate ?>">
<span class="invalid-feedback"><?php echo $joindate_err; ?></span>
</div>
the php tag above has this validations
//date validation
$input_joindate = trim($_POST["joindate"]);
if (empty($input_joindate)) {
$joindate_err = "Select join date";
}
if (!empty($input_joindate)) {
$input_joindate = date('Y-m-d', strtotime($input_joindate));
$today = strtotime("now");
if (($input_joindate) > $today)
$joindate_err = "Date should not be in the future";
} else {
$joindate = $input_joindate;
}
<?php
$today = date("Y-m-d");
$joindate = $_POST["joindate"];
if (empty($joindate) || !isset($joindate)) {
$joindate_err = "Select join date";
} elseif (strtotime($today) < strtotime($joindate)) {
$joindate_err = "Date should not be in the future";
}

PHP Add days to datetime based on form selection

I am trying to insert a datetime into my MySQL DB that adds a certain amount of time depending on what is selected from the form. For example, clicking the button on 2021-04-01 22:00:00 and selecting "1 day" would result in an entry in my DB of 2021-05-01 22:00:00, "3 Days" 2021-07-01 22:00:00 etc...
Here is what I have so far but I can't get it to work. Can anyone point me in the best direction? I've trimmed down my code to make it more readable, i think it makes sense though.
<?php
// Include config file
require_once "config.php";
$expire = "";
$expire_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Create a function to add + days to current datetime based on value selected one form and insert into DB column expire
//
$input_expire = trim($_POST["expire"]);
if ($input_expire = "1 Day" {
// add + 1 day
$expire_date = date('Y-m-d H:i:s');
$expire_date = date('Y-m-d H:i:s', strtotime($expire_date . ' +1 day'));
$expire = $expire_date;
echo $expire_date;
} elseif ($input_expire = "3 Day" {
// add + 3 day
$expire_date = date('Y-m-d H:i:s');
$expire_date = date('Y-m-d H:i:s', strtotime($expire_date . ' +3 day'));
$expire = $expire_date;
echo $expire_date;
} else ($input_expire = "5 Day" {
// add + 5 day
$expire_date = date('Y-m-d H:i:s');
$expire_date = date('Y-m-d H:i:s', strtotime($expire_date . ' +5 day'));
$expire = $expire_date;
echo $expire_date;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(empty($expire_err)){
$sql = ("INSERT INTO table (expire) VALUES ('$expire')");
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "sss", $param_expire);
// Set parameters
$param_tags = $expire;
if(mysqli_stmt_execute($stmt)){
header("location: index.html");
exit();
} else{
echo "Something went wrong";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Message</title>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Create Message</h2>
</div>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div <p style="width: 45%"; class="form-group <?php echo (!empty($expire_err)) ? 'has-error' : ''; ?>">
<label>Message Expiry</label>
<select class="form-control" name="expire"><?php echo $expire; ?>
<option value=""></option>
<option value="1 Day">1 Day</option>
<option value="3 Days">3 Days</option>
<option value="5 Days">5 Days</option>
</select>
<span class="help-block"><?php echo $expire_err;?></span>
</div>
<br>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
<br>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You have much problem in this code:
You didn't close ) in all if
All if use = instead of == (operators link)
In the form you write value like "5 Days" or "3 Days" but you try to catch "5 Day"
The last if you use else instead of elseif
Final Code:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Create function to add + days to current datetime based on value select on form and insert into DB column expire
//
$input_expire = trim($_POST["expire"]);
if ($input_expire == "1") {
// add + 1 day
$expire_date = date('Y-m-d H:i:s');
$expire_date = date('Y-m-d H:i:s', strtotime($expire_date . ' +1 day'));
$expire = $expire_date;
} elseif ($input_expire == "3") {
// add + 3 day
$expire_date = date('Y-m-d H:i:s');
$expire_date = date('Y-m-d H:i:s', strtotime($expire_date . ' +3 day'));
$expire = $expire_date;
} elseif ($input_expire == "5") {
// add + 5 day
$expire_date = date('Y-m-d H:i:s');
$expire_date = date('Y-m-d H:i:s', strtotime($expire_date . ' +5 day'));
$expire = $expire_date;
}
echo $expire;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Message</title>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Create Message</h2>
</div>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div <p style="width: 45%"; class="form-group <?php echo (!empty($expire_err)) ? 'has-error' : ''; ?>">
<label>Message Expiry</label>
<select class="form-control" name="expire"><?php echo $expire; ?>
<option value=""></option>
<option value="1">1 Day</option>
<option value="3">3 Days</option>
<option value="5">5 Days</option>
</select>
<span class="help-block"><?php echo $expire_err;?></span>
</div>
<br>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
<br>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I deleted some parts of code that were not needed by the post and I changed the values ​​with simple numbers so you already know that you want to use the days
On your journey toward programming greatness, I'd like to share some general best practices that you should adopt.
Don't Repeat Yourself -- when you see repeated patterns in your code, try to isolate the few differences that can be turned into variables then seek a technique to best use the variables. For example, your form and your submission handling code both need to be aware of the valid expiration options -- for this reason make a variable which both codes can leverage.
For security, stability, and consistency in your application, always use prepared statements when using variables as values in your sql. Use placeholders in your prepared statement and bind your variables to those placeholders -- otherwise you are failing to enjoy the benefits of prepared statements.
Use mysqli's object oriented syntax. It is less verbose and IMO easier to read.
A <select> tag, unless you are grouping options, should only have <option> tags for children. Don't try to squeeze any other text inside of the <select>.
When the text of an <option> is identical to its value attribute, don't bother declaring the value attribute.
Suggested and untested code:
$expiries = [
1 => '1 day',
3 => '3 days',
5 => '5 days',
];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$input_expire = $_POST["expire"] ?? '';
if (!isset($expiries[$input_expire])) {
$error = 'Missing/Invalid submission data';
} else{
$expire_date = date('Y-m-d H:i:s', strtotime("+{$input_expire} days"));
$stmt = $link->prepare("INSERT INTO table (expire) VALUES (?)");
$stmt->bind_param("s", $expire_date);
if (!$stmt->execute()) {
$error = "Failed to save";
} else{
header("location: index.html");
exit();
}
}
}
// ... further down the script ...
<select class="form-control" name="expire">
<option></option>
<?php
foreach ($expiries as $value => $text) {
printf('<option value="%s">%s</option>', $value, $text);
}
?>
</select>

Check date is today's date or yesterday's date

I want to insert data into table when selected date is Current Date or Yesterday's Date.
html code:
<input type="text" id="datepicker1" name="reportdate" class="gui-input" placeholder="Select Date" required="Select date" value="<?php echo date('d/m/Y'); ?>">
php code:
if(isset($_POST['submit'])){
$report_date=date('Y-m-d',strtotime($_POST['reportdate']));
$check_date=date('d',strtotime($_POST['reportdate']));
if($check_date!=date('d') or $check_date!=date('d')-1){
echo "<h2>You can only submit dcr of current date or yesterday.</h2>";
}
else{
$client=$_POST['CLIENT_NAME'];
//$cars_string = implode(', ', $_POST['cars']);
$productname_string=implode(', ',$_POST['productname']);
$remarks=$_POST['remark'];
$sql="insert into d_c_r (bm,date_time,client,promoted_product,remark) values ('".$_SESSION['id']."','$report_date',$client,'$productname_string','$remarks')";
$res=mysql_query($sql) or die(mysql_error());
}
}
Working Code Updated:
Working Demo: http://phpfiddle.org/main/code/fxh8-gnkw
<html>
<body>
<form action="" method="post" name="myform">
<input type="date" id="datepicker1" name="reportdate" class="gui-input" placeholder="Select Date" required="Select date" value="">
<button type="submit" name="submit"> Submit</button>
</form>
</body>
</html>
<?php
if(isset($_POST['submit']) && !empty($_POST['reportdate'])){
$today_date = date('d-m-Y'); // you get current date
$date_tday = new DateTime($today_date);
$date_tday->modify('-1 day');
$get_yesterday_date_from_current = $date_tday->format('d-m-Y'); // you get Yesterday date that from current date
$reportdate = $_POST['reportdate']; // you get report date that user is selected
$report_date_format = new DateTime($reportdate);
echo $report_date = $report_date_format->format('d-m-Y'); //you get report date that user is selected in d-m-Y
/*
$date = new DateTime($report_date);
$date->modify('-1 day');
echo $get_yesterday_date = $date->format('d-m-Y'); // you get Yesterday date that user is selected
*/
if($report_date !== $today_date && $report_date !== $get_yesterday_date_from_current){
echo "<h2>You can only submit dcr of current Date or Yesterday.</h2>";
}
else{
echo "Inser Your Data OR What You WAnt To Do HERE";
}
}
?>

PHP date input format

Created a PHP input form to POST dates into SQL query, on the server side we have 0000-00-00 date format but locally we use the 00/00/0000 format, how do get the input form to accept the 00/00/0000 format to be used in the SQL query? By now we force the users to put the 0000-00-00 and it works perfectly but a lot of them are complaining about that!
<form action="index.php" method="POST">
<cust>From: </cust><input name="start_date" placeholder=" 0000-00-00" />
<cust>Until: </cust><input name="end_date" placeholder=" 0000-00-00" />
<select name="RegioSelect" placeholder="Choose"><option></option>
<?php
$region = $_POST["RegioSelect"];
$fdate = $_POST["start_date"];
$edate = $_POST["end_date"];
if(empty($fdate)){
$fdate = '2000-01-01';
} else {
$fdate;
}
if(empty($edate)){
$edate = date("Y/m/d");
} else {
$edate;
}
We were thinking convert on server side but in that case we can't use dates to compare date ranges. We convert them after retrieving to user's info as follows:
$new_fdate = strtotime($fdate);
$FiDate = date('d/m/Y',$new_fdate);
changed '$edate' to date("Y-m-d");
$new_edate = strtotime($edate);
$EnDate = date('d/m/Y',$new_edate);
?>
<input type="submit" value="Select region">
</select></br>
</form>
<?php
if(empty($region)){
$region = ' ';
} else {?><h4><?php echo $region; ?></h4><cust><b>From:</b><?php echo $FiDate; ?> <b>Until:</b> <?php echo $EnDate; ?></cust>
<?php
}
?>
Solved this as follows, now it works other side around, the input form accept 00/00/0000 date format but get converted to server side once POSTED.
<form action="list.php" method="POST">
<cust>From: </cust><input name="start_date" placeholder=" 00/00/0000" />
<cust>Until: </cust><input name="end_date" placeholder=" 00/00/0000" />
<select name="RegioSelect" placeholder="Choose"><option></option>
<?php
$region = $_POST["RegioSelect"];
//ORIGINAL VARIABLES
/*$fdate = $_POST["start_date"];
$edate = $_POST["end_date"];
*/
$fdate = date_format(date_create_from_format('d/m/Y', $_POST["start_date"]), 'Y-m-d');
$edate = date_format(date_create_from_format('d/m/Y', $_POST["end_date"]), 'Y-m-d');
if(empty($fdate)){
$fdate = '01/01/2000';
} else {
$fdate;
}
if(empty($edate)){
$edate = date("Y/m/d");
} else {
$edate;
}
So the code tells the query to choose all data between $fdate and $edate, if $fdate is empty take 01/01/2000 as first date and if $edate is empty take TODAY() as end date.

build select list based on current date php

Ive created a drop select list that generates a list of dates based on the current date,
4 days back and 7 days forward, Ive tried several shorter scripts but they all fail, ive been using the following but it has some limitiations... Thanks!
<option value=""> select </option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-4),date("Y")));?>" style="color:red;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-4),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-3),date("Y")));?>" style="color:red;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-3),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-2),date("Y")));?>" style="color:red;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-2),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-1),date("Y")));?>" style="color:red;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-1),date("Y")));?></option>
<option value="<?php echo date ('m/d/Y');?>"><?php echo date ('m/d/Y');?> TODAY </option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+1),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+1),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+2),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+2),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+3),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+3),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+4),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+4),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+5),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+5),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+6),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+6),date("Y")));?></option>
<option value="<?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+7),date("Y")));?>" style="color:green;font-weight:bold;"><?php echo date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")+7),date("Y")));?></option>
This should do what you're asking. I've rewritten your code to make it as simple and readable as possible.
<?php
echo '<select>';
echo '<option value="">select</option>';
for($i = -4; $i <= 7; ++$i)
{
$date = date('m/d/Y', strtotime($i.' days'));
echo '<option value="'.$date.'" style="color:red;">'.$date.'</option>';
}
echo '</select>';
?>
What you should be doing is to create a function for your calculation,
so that you can use mydate(+1) , mydate(-2) in your code instead of that spaggheti.
Don't mix (and repeat) so much php code in your html, it is very bad practice and hard to maintain.
Second, inside your function you could turn your time to unix timestamp with appropriate function, add the number of miliseconds and turn it back to whatever time format you need.
Did you try
<?php
for($i = -4; $i <= 7; $i++) {
$date = date ("m/d/Y", mktime (0,0,0,date("m"),(date("d")-$i),date("Y")));
$date_txt = $date;
if($i == 0) {
$date_txt = "Today";
}
printf("<option value=\"%s\" style=\"color: red\">%s</option>", $date, $date_txt);
}
?>
This should suffice:
echo '<select><option> select </option>';
for($x=-4;$x<=7;$x++){
$date = date("m/d/Y",(time() + (86400 * $x)));
if($x<0){
$color='red';
}elseif($x==0){
$color = 'black;font-weight:bold';
}else{
$color = 'green';
}
echo '<option style="color:'.$color.'" value="'.$date.'">'.($x==0 ? 'TODAY':$date).'</option>';
}
echo '</select>';

Categories