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>
Related
I've got a form that loops (using while) all the months of the year in a drop-down. The value is the month in digits (m) and the text is the month in words (F). Everything displays correctly, yet when I post the form I'm getting a space after the 2 month digits. I've checked the form via an echo that the month digits are displaying without a trailing space, so it's definitely after posting. I've tried removing the trailing space with both "substr" and "rtrim" - neither remove the trailing space
Form code:
<div class="col-4">
<label for="phaseMonth" class="form-label ps-2 fw-bold">Draw-off Month</label>
<?php
$month = strtotime('2022-01-01');
$end = strtotime('2023-01-01');
$limonth = date('F', strtotime($row_lqe['drawoffDate']));
?>
<select name="phaseMonth" title="Select a Date" class="form-select border border-secondary" required>
<option value="">Select a Month</option>
<?php while ($month < $end) { ?>
<option value="<?php echo date('m', $month), PHP_EOL; ?>"
<?php if (!(strcmp(date('F', $month), $limonth))) {echo "selected=\"selected\"";} ?>>
<?php echo date('F', $month), PHP_EOL; ?>
</option>
<?php $month = strtotime("+1 month", $month); ?>
<?php } ?>
</select>
</div>
Post code:
$phaseMonth = $_POST['phaseMonth'];
if (empty($phaseMonth)) {
$newphaseMonth = "01";
} else {
$newphaseMonth = substr($phaseMonth, 0, -1);
}
$phaseYear = $_POST['phaseYear'];
if (empty($phaseYear)) {
$phaseYear = "2022";
}
$drawoffDate = $phaseYear . "-" . $newphaseMonth . "-01";
echo "$phaseMonth:$newphaseMonth:$phaseYear:$drawoffDate"; // to show trailing space
echo output:
11 :11 :2023:2023-11 -01
You seemed to miss the point about your excessive overuse of <?php and ?> tags; see this example and how much cleaner it is to view and work with:
<div class="col-4">
<label for="phaseMonth" class="form-label ps-2 fw-bold">Draw-off Month</label>
<?php
$month = strtotime('2022-01-01');
$end = strtotime('2023-01-01');
$limonth = date('F', strtotime($row_lqe['drawoffDate']));
print "<select name='phaseMonth' title='Select a Date'
class='form-select border border-secondary' required>
<option value=''>Select a Month</option>\n";
while ($month < $end) {
print "<option value='".date('m', $month)."'";
if (strcmp(date('F', $month), $limonth) === 0) {
echo "selected='selected'";
}
print ">".date('F', $month)."</option>\n";
$month = strtotime("+1 month", $month);
}
?>
</select>
</div>
Remove your PHP_EOL they're worthless here.
Use single and double quotes to double wrap quote marks rather than escaping quotes.
Use string concatenation . to streamline, as well as removing ?> <?php
This is a quick example only and can be further reduced but reduces readability.
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.
I have been searching for a while now, but I cannot put together enough information in order to resolve this problem.
I created an event calendar with a field that allows the user to enter a range for booking an event. I already have the start date configured for the date selected. When a user enters the end date, the information in the fields will be duplicated for each date in the range.
$requester = $_POST['txtrequester'];
$title = $_POST['txttitle'];
$detail = $_POST['txtdetail'];
$startTime = $_POST['txtstarttime'];
$endTime = $_POST['txtendtime'];
$endDate = $_POST['txtenddate']; //end date of range request
$eventdate = $month."/".$day."/".$year;
$today_dt = $year."-".$month."-".$day;
$startDate_dt = strtotime("$year."-".$month."-".$day");
$endDate_dt = strtotime($endDate);
$endDate_dt = $endDate_dt->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($today_dt, $interval, $endDate_dt);
Can someone help me figure this out? Thanks in advance
--Edit--
Code inserting event form data into mysql
$sqlinsert = "INSERT INTO conferenceevents (Requester,Title,Detail,eventDate,dateAdded,startTime,endTime,endRange) values ('$requester','$title','$detail','$eventdate',now(),'$startTime','$endTime','$endDate')";
$resultinsert = $connection->query($sqlinsert);
if($resultinsert){
echo "<h4>Event was Successfully Added</h4><br>";
}else{
echo "<h4>Event Failed to be Added</h4><br>" . $sqlinsert;
}
}
Event form html
<form name='eventform' method='POST' action="<?php $_SERVER['PHP_SELF']; ?>?month=<?php echo $month;?>&day=<?php echo $day;?>&year=<?php echo $year;?>&v=true&add=true">
<div class="form-group">
<label for="requester">Requester</label>
<select class="form-control" name='txtrequester'>
<option name='txtrequester'>Melissa</option>
<option name='txtrequester'>Greg</option>
<option name='txtrequester'>Matt</option>
<option name='txtrequester'>Michael</option>
<option name='txtrequester'>Ben</option>
<option name='txtrequester'>Pat</option>
<option name='txtrequester'>Maria</option>
</select>
</div>
<div class="form-group">
<label for="eventTitle">Event Title</label>
<input type="text" class="form-control" id="eventTitle" placeholder="Event Title" name='txttitle'>
</div>
<div class="form-group">
<label for="eventStartTime">Event Start Time</label>
<input type="time" class="form-control" id="eventStartTime" value="12:00" name='txtstarttime'>
</div>
<div class="form-group">
<label for="eventEndTime">Event End Time</label>
<input type="time" class="form-control" id="eventEndTime" value="13:00" name='txtendtime'>
</div>
<a href class="option"><h4>Click here to enter date range (optional)</h4></a>
<div class="form-group range" style="display: none;">
<label for="eventStartDate">Event Start Date</label>
<input type="text" class="form-control" id="disabledInput" name='txtstartdate' disabled value="<?php echo $month . "/" . $day . "/" . $year; ?>">
</div>
<div class="form-group range" style="display: none;">
<label for="eventEndDate">Event End Date</label>
<input type="date" value="<?php echo $year . "-" . $month . "-" . $day; ?>" class="form-control" id="eventEndDate" name='txtenddate'>
</div>
<div class="form-group">
<label for="eventDetail">Event Detail</label>
<input type="text" id="eventDetail" type="text" class="form-control" placeholder="Event Detail" name='txtdetail'>
</div>
<button type="submit" class="btn btn-default" name='btnadd'>Add Event</button>
</form>
It seems you are trying to insert a row in to your data base for each and every date in given date range... Please try it like this
$startTime = strtotime( '2015-01-11' );
$endTime = strtotime( '2015-01-20' );
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$given_date = date( 'Y-m-d', $i )."<br>";
// You can put your database insert query here
echo "Data for $given_date is inserted";
}
More efficient way of inserting multiple rows is as follows..
$startTime = strtotime( '2015-01-11' );
$endTime = strtotime( '2015-01-20' );
$sqlinsert = "INSERT INTO conferenceevents (Requester,Title,Detail,eventDate,dateAdded,startTime,endTime,endRange) values ";
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$eventdate =date('Y-m-d', $i );
// Constructing the insert query
$sqlinsert .= " ('$requester','$title','$detail','$eventdate',now(),'$startTime','$endTime','$endDate'),";
}
$bulk_insert_query = rtrim($sqlinsert, ","); // to remove last comma
$resultinsert = $connection->query($bulk_insert_query);
To get more understanding about bulk insert query Try to echo $bulk_insert_query and see how it was constructed and how you want to improve..
I am trying to create two drop downs with HTML and PHP. The first is an auto submit that sends a month to a session variable:
<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<option value="">-- Select Month --</option>
<?php $month = date('n'); // current month
for ($x = 0; $x < 12; $x++) { ?>
<option value="<?php echo date('m', mktime(0,0,0,$month + $x,1)); ?>"
<?php echo date('m', mktime(0,0,0,$month + $x,1)) == $_SESSION['month'] ? "selected='selected'":""; ?> >
<?php echo date('F Y', mktime(0,0,0,$month + $x,1)); ?>
<?php } ?>
</select>
</form>
This works great. But I then need a second drop down with the day name and number:
<form action="" method="post">
<select name="day" onchange="this.form.submit()">
<option value="">-- Select Day --</option>
<?php for ($i = $current_day; $i < 31; $i++) {
$tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i;
$weekday = date('D', strtotime($tmp_date)); { ?>
<option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
<?php echo $weekday." ".$i; ?>
<?php } ?>
<?php } ?>
</option>
<?php } ?>
</select>
</form>
This uses a temp date with a session variable as '2014' which I set before. I need to remove the session year variable and get the first drop down to know which year the month selected is and then pass this to the temp date so that it populates the day name and number correctly for the next year (2015) if you choose January onwards. At the moment it only shows the day name and number from the current year (2014) in this case.
<?php
if(isset($_POST)) {
$date = explode('-', $_POST['month']);
$year = $date[0];
$month = $date[1];
echo "Year: ".$year." Month: ".$month;
}
?>
<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<?php
for ($i = 0; $i <= 12; ++$i) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F Y', $time);
printf('<option value="%s">%s</option>', $value, $label);
}
?>
</select>
This gives me the year and month as separate values.
I had to check the print out of the first script, because it didn't make much sense...
<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<option value="">-- Select Month --</option>
<option value="11"
>
November 2014 <option value="12"
>
December 2014 <option value="01"
>
January 2015 <option value="02"
>
February 2015 <option value="03"
>
March 2015 <option value="04"
>
April 2015 <option value="05"
>
May 2015 <option value="06"
>
June 2015 <option value="07"
>
July 2015 <option value="08"
>
August 2015 <option value="09"
>
September 2015 <option value="10"
>
October 2015 </select>
</form>
Might be I'm missing something, because it seemed to work, but it doesn't seem like you're closing the option tags. You are doing this:
<option value="11">November 2014
<option value="12">December 2014
Instead of this:
<option value="11">November 2014</option>
<option value="12">November 2014</option>
This doesn't seem to be the issue though, at least not in chrome, because when I checked the head data being sent, it was just fine:
month: 11
What happens when you send in the variable is that whatever page you send this form data with the method POST against will have to handle it further on. In PHP you do that with the global variable $_POST, in this case $_POST['month'].
if(!empty($_POST['month']))
{
echo $_POST['month'];
}
If you want to make it a session variable, the page you send the form data to will have to communicate with your browser to set this (through the reply HTTP header field). To do anything related to session in PHP you must first start a session using the session_start() before any HTML/data is sent against the browser, and the same goes for if you want to set a session variable using for example session_set_cookie_params. You also got setcookie, which also must be used before any data/HTML is sent to the browser and the variables can be accessed through $_COOKIE.
See if you can make some sense out of this, I've just used $_POST in this case, you can swap it with session or cookie and remember to send it before any data/html to the browser.
<?php
$selmonth = 0;
if(!empty($_POST['month']))
{
$selmonth = $_POST['month'];
}
$month = date('n'); // current month
echo '<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<option value="">-- Select Month --</option>';
for($i=0; $i<12; $i++)
{
$monthtime = mktime(0,0,0,$month + $i,1);
$monthnum = date('m', $monthtime);
echo '
<option value="'.$monthnum.'"'.
($monthnum == $selmonth ? ' selected="selected"' : '').
'>'.date('F Y', $monthtime).'</option>';
}
echo '
</select>
</form>';
?>
<select required="" class="btn btn-warning btn-raised" onchange="loadMonthYear(this)">
<?php
$fdt = date('Y-m-1');
$tdt = date('Y-m-1', strtotime("-12 months"));
while (date('Ymd', strtotime($fdt)) >= date('Ymd', strtotime($tdt))) {
echo '<option value="'.date('M, Y', strtotime($fdt)).'"><a data-tag="' . date('M, Y', strtotime($fdt)) . '" href="javascript: void(0);">' . date('M, Y', strtotime($fdt)) . '</option>';
$fdt = date('Y-m-1', strtotime("-1 months", strtotime($fdt)));
}
?>
</select>
Im writing code practicing PHP if and else statements and form validation.
the basic idea is this:
After entering name, DOB , and email and clicking the submit button, Based on the DOB they enter the button leads them to leads to:
-a page telling them they are too young to drink (notwelcome.php)
OR
-a page telling them they can order a drink (welcome.php)
The 2 pages (notwelcome.php & welcome.php) are pulled from separate file called action.php saved like this:
<?php
include('welcome.php');
include('notwelcome.php');
?>
This is what i have been trying ..but its not working. nothing happens.. Its as if the if else code isnt even there :(
<?php
if ($_POST['submit']) {
$dob = $_POST['dob'];
if (isset ($_POST['dob'] )> 12/31/1992) {
header("Location: notwelcome.php");
} else {
header("Location: welcome.php");}
}
?>
Help. Im a beginner and i have hit a small bump in the road in my code.
additional infor:
HTML Code is like this:
<div style="text-align: center;">
<h2>FORM & PHP</h2>
<h3>WHINE & DINE</h3>
<form action="action.php" method="post">
Full Name: <input type="text" name="name"><br>
Date of Birth: <input type="date" name="dob"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" data-inline="true" value="Submit">
</form>
</div>
</div>
</form>
Try this. Also, you don't need to include those files unless you want them showing up on the page before you process the form. I would check to make sure you have the relative path correct. You would also want to make it so users enter the DOB in the right format.
<?php
if (isset($_POST['dob'])) {
$dob = $_POST['dob'];
if ($dob > date("m/d/Y", mktime(0, 0, 0, date('m'), date('d'), date('Y') - 21))) {
header("Location: notwelcome.php");
} else {
header("Location: welcome.php");}
}
?>
You can try this. In php code you can add additional if conditions to check validity of ranges.
<?php
if (isset($_POST['date']) && isset($_POST['month']) && isset($_POST['year']) )
{
$dob = date_format (date_create ($_POST['year']."-".$_POST['month']."-".$_POST['date']), "Y-m-d");
if ($dob > date("Y-m-d", mktime(0, 0, 0, date('m'), date('d'), date('Y') - 21)))
{
header("Location: notwelcome.php");
}
else
{
header("Location: welcome.php");
}
}
?>
<html>
<head></head>
<body>
<div style="text-align: center;">
<h2>FORM & PHP</h2>
<h3>WHINE & DINE</h3>
<form action="r.php" method="post">
Full Name: <input type="text" name="name"><br>
Date of Birth: <select name="month">
<option value="01">January</option><option value="02">February</option><option value="03">March</option>
<option value="04">April</option><option value="05">May</option><option value="06">June</option>
<option value="07">July</option><option value="08">August</option><option value="09">September</option>
<option value="10">October</option><option value="11">November</option><option value="12">December</option></select> <select name="date" >
<option value="1">01</option><option value="2">02</option><option value="3">03</option>
<option value="4">04</option><option value="5">05</option><option value="6">06</option>
<option value="7">07</option><option value="8">08</option><option value="9">09</option>
<option value="10">10</option><option value="11">11</option><option value="12">12</option>
<option value="13">13</option><option value="14">14</option><option value="15">15</option>
<option value="16">16</option><option value="17">17</option><option value="18">18</option>
<option value="19">19</option><option value="20">20</option><option value="21">21</option>
<option value="22">22</option><option value="23">23</option><option value="24">24</option>
<option value="25">25</option><option value="26">26</option><option value="27">27</option>
<option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option>
</select> <input name="year" type="text" id="year" size="4" maxlength="4"> <span>(YYYY)</span>
<br>
E-mail: <input type="text" name="email"><br>
<input type="submit" data-inline="true" value="Submit">
</form>
</div>
</body>
</html>
There's probably a more elegant way to do it, but this worked for me:
if(isset($_POST['dob'])) { $dob = $_POST['dob'];
list($date,$time) = explode(" ", $dob);
list($year,$month,$day) = explode("-",$date);
$years = date("Y") - $year;
$months = date("m") - $month;
$days = date("d") - $day;
if (($years > 21) || ($years == 21 && $months > 0) || ($years == 21 && $months == 0 && $days >= 0)) {
header("Location: welcome.php");
} else {
header("Location: notwelcome.php");
}
}
Subtracting the birth year from the current year, the birth month from the current month and the birth day from the current day, this basically runs up to three tests. First, if the current year is more than 21 years after the person's birth year, they're legal. Second, if it's 21 years after the person's birth year but it's after their birth month, they're legal. Finally, if it's 21 years after the person's birth year and it happens to be their birth month and the day of the month is greater than or equal to the person's birth day, they're legal. If none of those things are true, they're under 21.