I have a simple example of check box's which remember what has been selected after the form has been submitted and there is an error.
That part works great... but, I would like to post the resultant 'checked' boxes to my forms mail function.
What I have now only reports if its checked or unchecked I would prefer to have the checked box's 'value' without the unchecked box even registering.
<?php
$CB_1 = 'unchecked';
$CB_2 = 'unchecked';
$CB_3 = 'unchecked';
$CB_4 = 'unchecked';
$CB_5 = 'unchecked';
if (isset($_POST['submit'])) {
if (isset($_POST['CB_1'])) {$CB_1 = $_POST['CB_1'];
if ($CB_1 == 'item_01') {$CB_1 = 'checked';}
}
if (isset($_POST['CB_2'])) {$CB_2 = $_POST['CB_2'];
if ($CB_2 == 'item_02') {$CB_2 = 'checked';}
}
if (isset($_POST['CB_3'])) {$CB_3 = $_POST['CB_3'];
if ($CB_3 == 'item_03') {$CB_3 = 'checked';}
}
if (isset($_POST['CB_4'])) {$CB_4 = $_POST['CB_4'];
if ($CB_4 == 'item_04') {$CB_4 = 'checked';}
}
if (isset($_POST['CB_5'])) {$CB_5 = $_POST['CB_5'];
if ($CB_5 == 'item_05') {$CB_5 = 'checked';}
}
}
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "E-mail address not valid.";
}
} else {
$error .= "E-mail address is required.";
}
if (empty($error)) {
$from = 'From: '. #TEST .' <'. $email .'>';
$to = "someone#company.com";
$subject = "CHECKBOX TEST";
$content = "
checkbox selections:
check box 01: $CB_1
check box 02: $CB_2
check box 03: $CB_3
check box 04: $CB_4
check box 05: $CB_5
";
$success = mail($to,$subject,$content,$from);
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<?php if (!empty($error)) echo $error ?>
<br><br><br>
e-mail: <input type="text" name="email" value="<?php if (isset ($_POST {'email'})) { echo $_POST['email']; } ?>" />
<P>
<input type="checkbox" name="CB_1" value="item_01" <?PHP echo $CB_1; ?> /> Item 01
<input type="checkbox" name="CB_2" value="item_02" <?PHP echo $CB_2; ?> /> Item 02
<input type="checkbox" name="CB_3" value="item_03" <?PHP echo $CB_3; ?> /> Item 03
<input type="checkbox" name="CB_4" value="item_04" <?PHP echo $CB_4; ?> /> Item 04
<input type="checkbox" name="CB_5" value="item_05" <?PHP echo $CB_5; ?> /> Item 05
<P>
<input type="submit" name="submit" value="Submit"></input>
</form>
I know this may not necessarily answer the question but a way you could make your code more efficiant is do this.
for($i=1; $i<=5;$i++)
{
if(isset($_POST['submit'])&& isset($_POST['CB_'.$i]) && $CB_.$i=='item_0'.$i)
{
$CB_.$i = $_POST['CB_'.$i];
$CB_.$i = 'checked';
}
}
If you fix it that way it may also make it easier for us to debug.
okay, I found a way to do what I wanted but I'm fairly sure it's not the way someone who has real experience with PHP would do it. Any suggestions?
redelman431, thanks for your suggestion but it was really too advanced for my skill level.
<?php
if(isset($_POST['item_01'])) {$item_01 = 'Item 01';}
if(isset($_POST['item_02'])) {$item_02 = 'Item 02';}
if(isset($_POST['item_03'])) {$item_03 = 'Item 03';}
if(isset($_POST['item_04'])) {$item_04 = 'Item 04';}
if(isset($_POST['item_05'])) {$item_05 = 'Item 05';}
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "E-mail address not valid.";
}
} else {
$error .= "E-mail address is required.";
}
if (empty($error)) {
$from = 'From: '. #TEST .' <'. $email .'>';
$to = "someone#company.com";
$subject = "CHECKBOX TEST";
$content = "
checkbox selections:
checked box's: $item_01 $item_02 $item_03 $item_04 $item_05
";
$success = mail($to,$subject,$content,$from);
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<span style="color: red;"><?php if (!empty($error)) echo $error ?></span>
<br><br><br>
e-mail: <input type="text" name="email" value="<?php if (isset ($_POST {'email'})) { echo $_POST['email']; } ?>" />
<P>
<input type="checkbox" name="item_01" value="Item 01"
<?php if(isset($_POST['item_01'])) { echo 'checked'; } ?> /> Item 01
<input type="checkbox" name="item_02" value="Item 02"
<?php if(isset($_POST['item_02'])) { echo 'checked'; } ?> /> Item 02
<input type="checkbox" name="item_03" value="Item 03"
<?php if(isset($_POST['item_03'])) { echo 'checked'; } ?> /> Item 03
<input type="checkbox" name="item_04" value="Item 04"
<?php if(isset($_POST['item_04'])) { echo 'checked'; } ?> /> Item 04
<input type="checkbox" name="item_05" value="Item 05"
<?php if(isset($_POST['item_05'])) { echo 'checked'; } ?> /> Item 05
<P>
<input type="submit" name="submit" value="Submit"></input>
</form>
I found what I was looking for I suppose in the way of an array which I think 'redelman431' was trying to get me to do but it didn't make any sense to me at the time.
I then stumbled onto another array by 'David Bélanger' that for some reason made more sense to me so I used it into my check box's and it works fabulously.
the new problem is that I cant get the check box's that have been checked to remember that if there is an error elsewhere on the page which is a disaster as my final form has a ton of them.
Any ideas?
<?php
# Default Vars
$_group_01 = '';
if(isset($group_01) === TRUE){
# Is Array ?
if(is_array($group_01) === TRUE){
# Count
$c = count($group_01);
# Loop
for($i=0; $i < $c; $i++){
$_group_01.= (isset($group_01[$i]) === TRUE ? $group_01[$i] : '').($i == ($c-1) ? '' : ($i == $c-2 ? ' and ' : ', '));
}
}
}
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "E-mail address not valid.";
}
} else {
$error .= "E-mail address is required.";
}
if (empty($error)) {
$from = 'From: '. TEST .' <'. $email .'>';
$to = "someone#company.com";
$subject = "CHECKBOX TEST";
$content = "
checkbox selections:
Items Checked: $_group_01
";
$success = mail($to,$subject,$content,$from);
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<span style="color: red;"><?php if (!empty($error)) echo $error ?></span>
<br><br><br>
e-mail: <input type="text" name="email" value="<?php if (isset ($_POST {'email'})) { echo $_POST['email']; } ?>" />
<P>
<input type="checkbox" name="group_01[]" value="Item 01"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 01
<input type="checkbox" name="group_01[]" value="Item 02"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 02
<input type="checkbox" name="group_01[]" value="Item 03"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 03
<input type="checkbox" name="group_01[]" value="Item 04"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 04
<input type="checkbox" name="group_01[]" value="Item 05"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 05
<P>
<input type="submit" name="submit" value="Submit"></input>
</form>
Related
I'm trying to figure out how to apply a conditional to check if a year is a Leap year or Not. But when I add the leap function it just does not work.
Any idea how to make it work?
This is my code :
<?php
$name = "";
$character = "";
$email = "";
$birth_year = 1969;
$validation_error = "";
$existing_users = ["admin", "guest"];
$options = ["options" => ["min_range" => 1920, "max_range" => date("Y")]];
function leap($year) {
date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$raw_name = trim(htmlspecialchars($_POST["name"]));
if (in_Array($raw_name,$existing_users)){
$validation_error .= "This name is taken. <br>";
} else {
$name = $raw_name;
}
$raw_character = $_POST["character"];
if (in_array($raw_character,["wizard", "mage", "orc"])) {
$character = $raw_character;
} else {
$validation_error .= "You must pick a wizard, mage, or orc. <br>";
}
$raw_email = $_POST["email"];
if (filter_var($raw_email,FILTER_VALIDATE_EMAIL)) {
$email = $raw_email;
} else {
$validation_error .= "Invalid email. <br>";
}
$raw_birth_year = $_POST["birth_year"];
if (filter_var($raw_birth_year,FILTER_VALIDATE_INT,$options)){
$birth_year = $raw_birth_year;
if ($raw_character === "mage") {
if (!leap($birth_year)){
$validation_error .= "Mages have to be born on leap years. <br>";
}}
} else {
$validation_error .= "That can't be your birth year. <br>";
}
}
?>
<h1>Create your profile</h1>
<form method="post" action="">
<p>
Select a name: <input type="text" name="name" value="<?php echo $name;?>" >
</p>
<p>
Select a character:
<input type="radio" name="character" value="wizard" <?php echo ($character=='wizard')?'checked':'' ?>> Wizard
<input type="radio" name="character" value="mage" <?php echo ($character=='mage')?'checked':'' ?>> Mage
<input type="radio" name="character" value="orc" <?php echo ($character=='orc')?'checked':'' ?>> Orc
</p>
<p>
Enter an email:
<input type="text" name="email" value="<?php echo $email;?>" >
</p>
<p>
Enter your birth year:
<input type="text" name="birth_year" value="<?php echo $birth_year;?>">
</p>
<p>
<span style="color:red;"><?= $validation_error;?></span>
</p>
<input type="submit" value="Submit">
</form>
<h2>Preview:</h2>
<p>
Name: <?=$name;?>
</p>
<p>
Character Type: <?=$character;?>
</p>
<p>
Email: <?=$email;?>
</p>
<p>
Age: <?=date("Y")-$birth_year;?>
</p>
Im using this function to find if a year is Leap or not
function leap($year) {
date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
And this is the conditional that does not work :(
if ($raw_character === "mage") {
if (!leap($birth_year)){
$validation_error .= "Mages have to be born on leap years. <br>";
}}
I think your problem is the function is not returning anything, try :
function leap($year) {
return date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
I'm recieving an issue in the following php code. I am recieiving an unknown variable error in line 146, (echo $newrecord) variable. I'm not sure what is wrong with this variable, I have defined it in the IF statement, and am simply echoing if it is successful. I originally had that segment of code (after ) at the top of the script, but it was causing issues with the mandatory field error messages displaying properly. Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required"; }
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
echo $sub;
?>
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO newspaper (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} // end of nested if statement
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
newrecord is defined and initialized inside the if statement, therefore if your code opts to the else, it will skip the if and your newrecord variable won't exist.
$newrecord is defined within an if statement, when the if is not executed the variable is not available. You can define it by default adding $newrecord = ''; before you start the if for the submit.
I have about 12 check boxes in a form. I need to know which ones where checked when the data is sent to my email. The code below is my checkbox inputs. Can someone please tell me the php I need to send the value of each checkbox checked to my email? I have searched long and hard for at least 10 hours and I cannot figure it out. I had it working at one point, then I started to get an error message, so starting over with this because I dont even know the code I was using. I just want to know in the email that the php sends me which checkboxes are checked. Here is the part of the form below with the list of checkboxes.
<p>
<input type="checkbox" name="service[]" <?php echo $selected['regularMaintenance'] ?> value="regularMaintenance" /><span class="checkboxlabel">Regular Maintenance</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['equipmentRental'] ?> value="equipmentRental" /><span class="checkboxlabel">Equipment Rental</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['snowManagement'] ?> value="snowManagement" /><span class="checkboxlabel">Snow Management</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['windowCare'] ?> value="windowCare" /><span class="checkboxlabel">Window Care</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['aeration'] ?> value="aeration" /><span class="checkboxlabel">Aeration</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['gutterCleaning'] ?> value="gutterCleaning" /><span class="checkboxlabel">Gutter Cleaning</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['powerRake'] ?> value="powerRake" /><span class="checkboxlabel">PowerRake</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['sodding'] ?> value="sodding" /><span class="checkboxlabel">Sodding</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['treeSpraying'] ?> value="treeSpraying" /><span class="checkboxlabel">Tree Spraying</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['springCleanup'] ?> value="springCleanup" /><span class="checkboxlabel">Spring Clean Up</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['fallCleanup'] ?> value="fallCleanup" /><span class="checkboxlabel">Fall Clean Up</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['fertilize'] ?> value="fertilize" /><span class="checkboxlabel">Fertilizing</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['sprinklerwinterization'] ?> value="sprinklerwinterization" /><span class="checkboxlabel">Sprinkler Winterization</span>
</p>
<p>
<input type="checkbox" name="service[]" <?php echo $selected['other'] ?> value="other" /><span class="checkboxlabel">Other</span>
</p> enter code here
My form's action code is: action="
...and here is my php validation and send to emal code. I dont know anythiing about php, and I forgot where to add the code that you told me. I have one part that says foreach
($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
which keeps the checkboxes checked when the form is sumitted and there is an error so it returns back to the form. This part doesnt give me an error though, but if I use in my
`$message:
Services Selected: " . $selectedService . "
and they check more than one box, I only get one of the boxes they checked.
so here is my php code. I m sure that I am placing something somewhere wrong or something.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
Place this code in the code where the post is processed (i assume the mail is html):
$message = "checkboxes:<br>\n";
$i = 1;
foreach ($_POST['service'] as $checkbox) {
$checked = $checkbox ? '1' : '0';
$message .= 'checkbox'.$i++.' : '. $checked."<br>\n";
}
then, add the $message to the mail body.
I need help working with Checkboxes and PHP. I'm just trying to determine a value on whether the checkbox is checked or not with PHP.
Example:
<?php
include ("inc/conf.php");
$id = $_SESSION['id'];
if(isset($_POST['subfrm'])){
$gtid = $_REQUEST['tid'];
$ch1 = $_REQUEST['ch1'];
if($ch1 == "ON"){
$gch1 = "Y";
} else {
$gch1 = "N";
}
$ch2 = $_REQUEST['ch2'];
if($ch2 == "ON"){
$gch2 = "Y";
} else {
$gch2 = "N";
}
mysql_query("UPDATE SET ctable ch1='$gch1', ch2='$gch2' WHERE id='$gtid'");
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="tid" value="<?php echo $id; ?>" />
<input type="checkbox" name="ch1" />Hats
<input type="checkbox" name="ch2" />Watches
<textarea name="thetext"></textarea>
<input type="submit" name="subfrm" value="PUNCH ME" />
</form>
if(isset($_REQUEST["ch1"])){
$gch1 = "Y";
} else {
$gch1 = "N";
}
if(isset($_REQUEST["ch2"])){
$gch2 = "Y";
} else {
$gch2 = "N";
}
You don't need to check to see what the value is, because it will not submit any data whatsoever if it isn't checked, and it will submit a value of on if it is.
Try this:
<?php
$ch1 = isset($_REQUEST['ch1']);
If the check box wasn't checked, its corresponding variable won't show up in the request.
Through this together. It will let you know which checkbox was selected and it will also retain the check on form submit.
<?php
$message = '';
$ch1_checked = false;
$ch2_checked = false;
if(isset($_POST['submit_button'])) {
// Form was submitted
$ch1_checked = isset($_POST['ch1']);
$ch2_checked = isset($_POST['ch2']);
if($ch1_checked && $ch2_checked) {
$message .= 'Both were checked.';
} else if($ch1_checked) {
$message .= 'Checkbox 1 was checked.';
} else if($ch2_checked) {
$message .= 'Checkbox 2 was checked.';
} else {
$message .= 'Neither were checked.';
}
}
?>
<?php echo $message; ?>
<form id="my_form" action="test.php" method="post">
<input type="checkbox" name="ch1" value="ch1" <?php if($ch1_checked) echo 'checked'; ?> />Checkbox 1<br />
<input type="checkbox" name="ch2" value="ch2" <?php if($ch2_checked) echo 'checked'; ?> />Checkbox 2<br />
<input type="submit" name="submit_button" value="Go!" />
</form>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$gender = $_POST["gen"];
$age = $_POST["age"];
$comments = $_POST["comments"];
if(empty($_POST["name"])){
echo "empty name";
}
if(empty($_POST["email"])){
echo "empty email";
}
///
if(empty($_POST["gen"])){
echo "empty gender";
}
if(empty($_POST["comments"])){
echo "empty comments";
}
if(!isset($_POST['submit'])) {
?>
<html>
<head>
<title>Lab6 : P1</title>
</head>
<body>
<fieldset>
<legend><h4>Enter your information in the fields below</h4></legend>
<form name="info" method="post" action="<?php echo $PHP_SELF;?>" method="post">
<strong>Name:</strong> <input type="text" name="name" id="name" /><br>
<strong>Email:</strong> <input type="text" name="email" id="email" /><br>
<br>
<strong>Gender</strong><br>
<input type="radio" name="gen" value="Male">Male</input><br>
<input type="radio" name="gen" value="Female">Female</input><br>
<br>
<select name="age">
<option value="Under 30">Under 30</option><br>
<option value="Between 30 and 60">Between 30 and 60</option><br>
<option value="60+">60+</option>
</select>
<br>
Comments: <textarea name="comments" cols="20" rows="5"> </textarea>
</fieldset>
<input type="submit" name="submit" value="Submit my Information" />
</form>
</body>
</html>
<?
}
else {
echo "Thank you, ".$name." for your comments: " . "<strong>" . $comments . "</strong>";
echo "<br>We will reply to you at:" . "<em>" . $email . "</em>";
}
?>
I need it to validate the fields: name, email, comments for empty strings (not allowed) and not allow unselected radio buttons for gender and age selection.
Can anyone help
<?php
// to eventually re-fill the fields
$name = "";
$email = "";
$gender = "";
$age = "";
$comments = "";
// to re-select a radio button and select option
$Mchecked = "";
$Fchecked = "";
$selectMinus_30="";
$select30_to_60="";
$select60_plus="";
// to display errors
$error = "";
$done=false;
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["age"])){
if($_POST["name"]==""){
$error = "empty name <br/>";
}
if($_POST["email"]==""){
$error = $error . "empty mail <br/>";
}
if(!isset($_POST["gen"])){
$error = $error . "empty gender <br/>";
}
else{
$gender = $_POST["gen"];
if ($gender == "Male"){
$Mchecked = "checked";
}
else if ($gender == "Female"){
$Fchecked = "checked";
}
}
if($_POST["comments"]==""){
$error = $error . "error: empty comments <br/>";
}
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
$age = $_POST["age"];
if ($age == "Under 30"){
$selectMinus_30 = "selected";
}
else if ($age == "Between 30 and 60"){
$select30_to_60 = "selected";
}
else if ($age == "60+"){
$select60_plus = "selected";
}
if ($error==""){
$done=true;
}
}
?>
<html>
<head>
<title>Lab6 : P1</title>
</head>
<body>
<?php if (!$done){ ?>
<fieldset>
<legend><h4>Enter your information in the fields below</h4></legend>
<p class="error" style="color:red;"><?php echo $error;?></p>
<form name="info" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<strong>Name:</strong> <input type="text" name="name" id="name" value="<?php echo $name; ?>" /><br/>
<strong>Email:</strong> <input type="text" name="email" id="email" value="<?php echo $email; ?>" /><br/>
<br/>
<strong>Gender</strong><br/>
<input type="radio" name="gen" value="Male" <?php echo $Mchecked;?>>Male</input><br/>
<input type="radio" name="gen" value="Female" <?php echo $Fchecked;?>>Female</input><br/>
<br/>
<select name="age" value="<?php echo $age;?>">
<option value="Under 30" <?php echo $selectMinus_30;?>>Under 30</option><br/>
<option value="Between 30 and 60" <?php echo $select30_to_60;?>>Between 30 and 60</option><br/>
<option value="60+" <?php echo $select60_plus;?>>60+</option>
</select>
<br/>
Comments: <textarea name="comments" cols="20" rows="5"><?php echo $comments; ?></textarea>
</fieldset>
<input type="submit" name="submit" value="Submit my Information" />
</form>
<?php }else{
echo "Thank you, ".$name." for your comments: " . "<strong>" . $comments . "</strong>";
echo "<br/>We will reply to you at:" . "<em>" . $email . "</em>";
} ?>
</body>
</html>
Here I did proper validation, and also re-fill the form when you submit with any empty field.
P.S. Thank you Marc B , I didn't realize that my first post was aweful.