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.
Related
I am new in PHP. I am creating a project. In this project, I want to fetch information of users who have not deposited money/payment yet in this month and year. My code is not working properly. I just want to show the username of those who have not deposited money/payment this month and year.
maybe need an IF/else formula but I don't know. please help.
usename unique see the table
table_name=credit
inserted rows like
usename
month
Year
A
November
2022
B
November
2022
B
December
2022
user A and B both are submit payment previous month and year, this month and year user B submit payment, but user A not submit payment. I want to show user A. my acceptation output given below
usename
month
Year
A
November
2022
<form method="post" accept="" class="row g-3">
<div class="col-lg-4">
<label for="val-select2">Month <span class="text-danger">*</span></label>
<select class="js-select2 form-select form-control" id="val-select2" name="pay_month" style="width: 100%;" required>
<option value="<?php echo date("F")?>" hidden><?php echo date("F")?></option>
<option value="January">January</option>
<option value="February">February </option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
</div>
<div class="col-lg-4">
<label >Year<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="pay_year" placeholder="year" required value="<?php echo date("Y");?>
">
</div>
<div class="col-lg-2">
<label></label>
<button class="form-control btn btn-primary" name="save" type="submit"><i class="fa fa-eye" aria-hidden="true"></i>
View</button>
</div>
</form>
<?php
if (isset($_POST['save'])) {
$sql = "SELECT * FROM credit WHERE NOT (pay_month='" . $_POST['pay_month'] . "' AND pay_year='" . $_POST['pay_year'] . "') ORDER BY username";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
$count = 0;
while($row = mysqli_fetch_array($result)){
if(mysqli_num_rows($result) > 0)
$count ++;
echo '<tr id="'.$row["id"].'">';
echo '<td class="fw-semibold">'.$count.'
</td>';
echo '<td class="fw-semibold fs-sm text-success"> '.$row["username"].'
</td>';
echo "</tr>";
}
mysqli_free_result($result);
} else{
echo "No data found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}} ?>
I think you have to change your SQL to look for the number of payments in the desired period and to filter by those with 0 payment.
Something like :
SELECT username, COUNT(*) AS n FROM credit
WHERE month = ? AND year = ? HAVING n=0;
(I used prepared statement in the example)
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>
So I have an AJAX process that submits a variable from a select option in a HTML form, and then builds another select menu from that. Essentially what is supposed to happen is that, for example, if the user selects the month of Feburary, the variable sent to the PHP script will be '02' and then the new dropdown box will have 29 options. The problem is that, despite my script telling me that 02 has been sent, the days are all out of whack. The days don't seem to correlate to the months, however despite the days being wrong, they're always consistently wrong. For example, while Feburary doesn't print 29 days, it will always consistently print the '30' days option, no matter whether it's 30, or 8000.
Here is my javascript file:
$(document).ready(function() { //Makes sure page is loaded.
/* === LINKS ===
Controls the links (site behaviour) via JQuery (as
defined by the Assignment CRA).
*/
$('#home').html('Home');
$('#signup').html('Sign Up');
$('#activities').html('Upcoming Activities');
$('#feedback').html('Student Feedback');
$('#contact').html('Contact');
/* === STAFF INFORMATION TOGGLE ===
Displays or hides information about
staff members on click.
*/
/*
$('#spongeimage').click(function() {
$("#spongeinfo").slideToggle("slow");
});*/
$(".staff").click(function() {
//alert("ALERT");
$(".staffinfo", this).slideToggle("slow");
});
$('#year').change(function() {
$("#month").slideToggle("slow");
});
$('#month').change(function() {
var month_var = $("#month").val();
var dataString = 'name1='+ month_var;
//Start
$.ajax({
type: "POST",
url: "./javascript/month_post.php",
data: dataString,
dataType: "text",
success: function(data) {
//alert(dataString);
$("#day").html(data);
$("#okay").html(dataString);
}
});
//End
$("#day").slideToggle("slow");
});
/* === 'FIRST NAME' FORM FOCUS
Focuses the cursor on the 'first name'
field when the Student Feedback page
is loaded.
*/
$('input[name="firstname"]').focus();
/* === HOVER EFFECTS ===
The effects that occur after hovering over
an item on the link bar (1.0) and one of
the two buttons on the Student Feedback
page (1.1).
*/
//(1.0)
$("li a").hover(function(){
$(this).css({"color": "#000000", "background-color": "#5590ff"});
}, function(){
$(this).css({"color": "#333", "background-color": "#FFFFFF"});
});
//(1.1)
$("formbutton").hover(function(){
$(this).css({"color": "#000000", "background-color": "#5590ff"});
}, function(){
$(this).css({"color": "#333", "background-color": "#FFFFFF"});
});
});
Here is my PHP file:
<?php
echo $name;
if(isset($_POST["name1"]))
{
$name = $_POST["name1"];
//echo $name;
// Here, you can also perform some database query operations with above values.
//echo "Welcome ". $name ."!"; // Success Message
$counter = 1;
//echo "<select name='gday'>";
if($name == 02)
{
$monthdays = 29;
}
if($name == 06 || $name == 09 || $name == 04 || $name == 11)
{
$monthdays = 30;
}
else
{
$monthdays = 31;
}
while ($counter <= $monthdays)
{
echo "<option value='hi'>".$counter."</option>";
$counter++;
}
//echo "</select>";
}
?>
And here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<title>KIT411 - Homepage</title>
<link rel="stylesheet" href="./CSS/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./javascript/script.js"></script>
</head>
<body>
<!-- TITLES -->
<div class="titles">
<!-- Blank character, to ensure the titles div extends to the top of the page. -->
<h1 class="title">KIT411</h1> <!-- Unit name. -->
<h2 class="subtitle">Sign Up</h2> <!-- Page name. -->
</div>
<div class="right">
<?php
include('login.php');
?>
</div>
<!-- PAGE LINKS
Links are controlled by JQuery, which is why
there are no <a></a> tags. -->
<?php
include('PHP/linkbar.php');
?>
<div class="center">
<div class="inline">
<?php
include('./db-connection/register.php');
?>
<div id="okay">TEST </div>
<form method="post" action="">
Username:<br>
<input type="text" name="usr" value="<?php echo $user; ?>"><br>
Password:<br>
<input type="password" name="pass" value="<?php echo $password; ?>"><br>
Retype Password:<br>
<input type="password" name="pass2" value="<?php echo $passwordTwo; ?>"><br>
Name:<br>
<input type="text" name="name" value="<?php echo $name; ?>"><br>
DOB:<br>
<select id="day" name="dobDay">
<?php
$counter = 1;
while($counter <= 31)
{
?>
<option value="<?php echo $counter; ?>"><?php echo $counter; ?></option>
<?php
$counter++;
}
?>
</select>
<select id="month" name="dobMonth">
<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 id="year" name="dobYear">
<?php
$counter = 1100;
while($counter <= 2016)
{
?>
<option class="yearClass" value="<?php echo $counter; ?>"><?php echo $counter; ?></option>
<?php
$counter++;
}
?>
</select>
<br>
Email:<br>
<input type="text" name="email" value="<?php echo $email; ?>"><br>
<input type="submit" name="submit" value="Sign Up">
</form>
</div>
</div>
<?php
include('PHP/footer.php');
?>
</body>
</html>
Any help would be greatly appreciated, and sorry if there's any swearwords in my code. Sometimes I do it for a bit of fun while testing and forget to remove them. Anyway, any help is progress.
The problem is in the PHP code, when you try to set up the number of days. You have one if and one if ... else, but doesn't behave as you expect.
You have first this if
if($name == 02)
{
$monthdays = 29;
}
And after this one:
if($name == 06 || $name == 09 || $name == 04 || $name == 11)
{
$monthdays = 30;
}
else
{
$monthdays = 31;
}
This last one will set up the number of days to 30 or 31, because it only have two choices. Here you could use an elseif control structure. http://php.net/manual/en/control-structures.elseif.php
if ($name == 02)
{
$monthdays = 29;
}
else if ($name == 06 || $name == 09 || $name == 04 || $name == 11)
{
$monthdays = 30;
}
else
{
$monthdays = 31;
}
I am currently working with an simple php code with validation and this is my code:
<form action="" method="post">
<input type="text" name="name" id="name" placeholder="Name">
<br>Number of Books:<select id="books" name="books">
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
<option> 4 </option>
<option> 5 </option>
<option> 6 </option>
<option> 7 </option>
<option> 8 </option>
<option> 9 </option>
<option> 10 </option>
</select>
</br>dutedate <input type="date" name="duedate" id="duedate" placeholder="duedate">
</br>borrow <input type="date" name="datebor" id="datebor" placeholder="dateborrowed">
</br>return <input type="date" name="ret" id="ret" placeholder="date returned">
<input type="submit" class="button" name="btnsubmit" value="Submit">
</form>
<?php
if (isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$duedate = date_create(($_POST['duedate']));
$datebor = date_create(($_POST['datebor']));
$ret = date_create(($_POST['ret']));
$books = $_POST['books'];
$NOWdate = new Datetime('now');
if ($duedate < $datebor)
{
echo "<script>alert('Wrong Input Error1')</script>";
exit;
}
elseif ($datebor > $ret)
{
echo "<script>alert('Wrong Input Error2')</script>";
exit;
}
elseif ($datebor > $NOWdate )
{
echo "<script>alert('Wrong Error3')</script>";
exit;
}
elseif ($ret < $duedate)
{
$penalty = 0 ;
}
else
{
$penaltydays = date_diff($duedate,$ret) ;
$diff_date = $penaltydays->format('%a');
$penalty = $diff_date * $books * 10;
}
}
?>
<p>Penalty: <?php echo $penalty ?></p>
When I try to run it, there is an error Undefined variable: penalty.
I am pretty sure that my validation codes are correct
How could I pass the penalty variable to the page itself.
I think it would resolve the error.
The problem is that the $penalty is only set after you submit the form. You should be able to fix this by simply moving the penalty paragraph inside your elseif/else blocks where a penalty should actually be shown.
...
elseif ($ret < $duedate)
{
echo "<p>Penalty: 0</p>";
else
{
$penaltydays = date_diff($duedate,$ret) ;
$diff_date = $penaltydays->format('%a');
$penalty = $diff_date * $books * 10;
echo "<p>Penalty: $penalty</p>";
}
This way it will only be displayed if it has been calculated.
Side note, I don't think this will work the way you are expecting it to because your select options do not have value attributes. You need to add them like this:
<option value="1"> 1 </option>
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>