Function to check if input field is empty - php

I'm trying to validate a form field.
The function validate_emp checks if the input field is empty. I want to know why it's not working.
$first_name = $middle_name = $last_name = $gender = $email = "";
$first_nameErr = $middle_nameErr = $last_nameErr = $genderErr = $emailErr="";
function validate_emp($input_name, $error_mess, $field_name){
if(empty($_POST[$field_name])){
$error_mess = "This field is must not empty.";
}else{
$input_name = $_POST[$field_name];
}
}
if(isset($_POST["btnregister"])){
validate_emp($first_name, $first_nameErr, "first_name");
validate_emp($middle_name, $middle_nameErr, "middle_name");
validate_emp($last_name, $last_nameErr, "last_name");
validate_emp($gender, $genderErr, "gender");
validate_emp($email, $emailErr, "email");
}
This is the form that I've created
<form method="POST">
First Name: <input type="text" name="first_name" placeholder="First Name" value="<?php echo $first_name ?>"> <span class="error"> <?php echo $first_nameErr ?> </span><br>
Middle Name: <input type="text" name="middle_name" placeholder="Middle Name" value="<?php echo $middle_name ?>"> <span class="error"> <?php echo $middle_nameErr ?> </span><br>
Last Name: <input type="text" name="last_name" placeholder="Last Name" value="<?php echo $last_name ?>"> <span class="error"> <?php echo $last_nameErr ?> </span><br>
<select name="gender">
<option name="gender" value="">Gender</option>
<option name="gender" <?php if($gender == "Male") { echo "Selected"; }?> value="Male">Male</option>
<option name="gender" <?php if($gender == "Female") { echo "Selected"; }?> value="Female">Female</option>
</select> <span class="error"> <?php if ($gender == "") {echo $genderErr;} ?> </span> <br>
Email: <input type="text" name="email" value="<?php echo $email ?>"><span class="error"> <?php echo $emailErr ?> </span><br>
<input type="submit" name="btnregister" value="Register">
</form>

You haven't returned anything from the function try returning something.
function validate_emp($input_name, $error_mess, $field_name){
if(empty($_POST[$field_name])){
$error_mess = "This field is must not empty.";
}else{
$input_name = $_POST[$field_name];
}
return //
}

I think the problem is that when you do:
validate_emp($first_name, $first_nameErr, "first_name");
validate_emp($middle_name, $middle_nameErr, "middle_name");
validate_emp($last_name, $last_nameErr, "last_name");
validate_emp($gender, $genderErr, "gender");
validate_emp($email, $emailErr, "email");
the first and second parameters of the function are using variables that aren't defined.
I can see you are using them as variables by reference, and in order to do so you must use them with & before them, if I where you I would return empty or the value and evaluate that:
function validate_emp($field_name){
if(empty($_POST[$field_name])){
$output = "";
}else{
$output = $_POST[$field_name];
}
return $output;
}
Then outside of the function:
$first_name = validate_emp("first_name");
if ($first_name == "") { echo "$first_name cannot be empty"; }

Related

Updating a specific row in an SQL table selected by a drop-down list in PHP

I've been making a Car Parking System for a school project, and I've been stuck on this problem for a while now. The goal of the project is to have a maximum of 10 parking slots, where the user is able to select which slot they want to be in from a drop-down box. So far, I've managed to get the drop-down box to show along with the 10 parking slots, but I could never get it to update on the row selected on the drop-down box. Here are my codes so far:
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"]))
{
$CustomerNameErr = "Please fill out this field";
}
else
{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"]))
{
$PlateNumberErr = "Please fill out this field";
}
else
{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"]))
{
$CarNameErr = "Please fill out this field";
}
else
{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"]))
{
$CarColorErr = "Please fill out this field";
}
else
{
$CarColor = $_POST["CarColor"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='".$rows['Slot']."'>".$rows['Slot']."</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$SlotVal' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
} ...
Nothing happens when I try to submit the update form. The data I type in doesn't seem to go anywhere at all, but it still executes the query since the javascript alert is working. I don't know what I'm missing here. Any help would be appreciated!
EDIT: I fixed a little bit of the code and now instead of nothing happening, it just keeps on updating the 10th slot no matter which slot i select on the dropdown.
Below is an updated code please replace it with this updated code.
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"])){
$CustomerNameErr = "Please fill out this field";
}else{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"])){
$PlateNumberErr = "Please fill out this field";
}else{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"])){
$CarNameErr = "Please fill out this field";
}else{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"])){
$CarColorErr = "Please fill out this field";
}else{
$CarColor = $_POST["CarColor"];
}
if(empty($_POST["slots"])){
$SlotErr = "Please fill out this field";
}else{
$Slot = $_POST["slots"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='$SlotVal'>$SlotVal</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$Slot' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
}
You are missing a part where should you accept the $_POST['slots']
if(empty($_POST["slots"]))
{
$slotErr = "Please select value for this field";
}
else
{
$slot = $_POST["slots"];
}

How to get information from an already populated form

I am trying to update a database record using a submit button, however the form that information is being taken from has itself been populated by another submit button.
The PHP is below:
if (isset($_POST['edit']))
{
$editUser = User::locate($_POST['userSelect']);
$setCompany = Company::findCompany();
$exCompanyId = $editUser->user_company_id;
$isAdmin = $editUser->user_admin;
$eUserFirstname = $editUser->user_firstname;
$eUserLastname = $editUser->user_lastname;
$eUserUsername = $editUser->user_username;
$eUserEmail = $editUser->user_email;
$eUserCompany = $editUser->user_company;
$adminArray = array("Yes","No");
if ($exCompanyId > NULL)
{
$exCompany = Company::locateId($exCompanyId);
$companyValue = $exCompany->company_name;
}
else
{
$companyValue = "";
}
if ($isAdmin > 0)
{
$userAdmin = $adminArray[0];
}
else
{
$userAdmin = $adminArray[1];
}
}
if (isset($_POST['confirm']))
{
$updateUserRecord = User::locate($eUserUsername);
$newCompanyValue = $_POST['setCompany'];
$isAdmin = $_POST['userAdmin'];
$newCompany = Company::locate($newCompanyValue);
$companyId = $newCompany->company_id;
$updateUserRecord->user_company_id = $companyId;
$updateUserRecord->user_admin = $isAdmin;
$editUser->updateUserAdmin();
$message = "You have successfully updated the user account";
echo "<script type='text/javascript'>alert('$message');</script>";
}
The HTML code is below:
<form action="" method="post">
<p>
<label>First Name:</label>
<label><?php echo $eUserFirstname ?></label>
</p>
<p>
<label>Last Name:</label>
<label><?php echo $eUserLastname ?></label>
</p>
<p>
<label>Username:</label>
<label><?php echo $eUserUsername ?></label>
</p>
<p>
<label>Email Address:</label>
<label><?php echo $eUserEmail ?></label>
</p>
<p>
<label>User Company:</label>
<label><?php echo $eUserCompany ?></label>
</p>
<p>
<label>Set Company:</label>
<select name="setCompany">
<option><?php echo $companyValue ?></option>
<?php
foreach ($setCompany as $srow)
{
?>
<option id="<?=
$srow->company_id
?>">
<?=
$srow->company_name
?>
</option>
<?php
}
?>
</select>
</p>
<p>
<label>Administrator:</label>
<select name="userAdmin">
<option><?php echo $userAdmin ?></option>
<?php
foreach ($adminArray as $arow)
{
?>
<option>
<?=
$arow
?>
</option>
<?php
}
?>
</select>
</p>
<input type="submit" name="cancel" value="Cancel">
<input type="submit" name="confirm" value="Confirm">
</br>
</form>
From my investigations so far the variables aren't transferring to the 2nd if statement, and I'm not sure how to make them available to it.
Store the first form's submission in hidden input fields alongside your echo statements. For example: <input type="hidden" name="field_name" value="<?php echo htmlspecialchars($field); ?>">
Or, alternatively, update the DB after first form posts.

How to create a selection dropdown in php form

I am working on a project and would like to give the user per-determined values when updating a record.
Here is my code so far.
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$Name = mysql_real_escape_string(htmlspecialchars($_POST['Name']));
$Status = mysql_real_escape_string(htmlspecialchars($_POST['Status']));
$Comments = mysql_real_escape_string(htmlspecialchars($_POST['Comments']));
$Type = mysql_real_escape_string(htmlspecialchars($_POST['Type']));
// check that firstname/lastname fields are both filled in
if ($Name == '' || $Type == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $Name, $Status, $Comments, $Type, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE Schools SET Name='$Name', Status='$Status', Comments='$Comments', Type='$Type' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM Schools WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$Name = $row['Name'];
$Status = $row['Status'];
$Comments = $row['Comments'];
$Type = $row['Type'];
// show form
renderForm($id, $Name, $Status, $Comments, $Type, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
I am wanting to replace the status text filed with a drop down list of options.
Replace your <input by <select :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<option value="1">Status 1</option>
<option value="2">Status 2</option>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
If your statuses are in a table, fill the <select> with a query :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<?php
$result = mysql_query("SELECT * FROM tbl_status",$cnx);
while ( $row = mysql_fetch_array($result) )
echo "<option value='" . $row["id"] . "'>" . $row["text"] . "</option>";
?>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
You could use the html <datalist> or the <select> tag.
I hope I could help.
First of all you need to switch from mysql_* to mysqli_* as it going to get removed in php 7.0 I'm using this function i created and it might help you
here is the php code
function GetOptions($request)
{
global $con;
$sql = "SELECT * FROM data GROUP BY $request ORDER BY $request";
$sql_result = mysqli_query($con, $sql) or die('request "Could not execute SQL query" ' . $sql);
while ($row = mysqli_fetch_assoc($sql_result)) {
echo "<option value='" . $row["$request"] . "'" . ($row["$request"] == $_REQUEST["$request"] ? " selected" : "") . ">" . $row["$request"] . "$x</option>";
}
}
and the html code goes like
<label>genre</label>
<select name="genre">
<option value="all">all</option>
<?php
GetOptions("genre");
?>
</select>

How to output all checkbox value

hello please help me i have a problem outputting all the values of checkbox it outputs only one i need to show all the checked checkbox and output them please help me here is the code it only shows one whenever i checked them all i need this
<html>
<head>
<title>Cake Form</title>
<link rel="stylesheet" href="cakeform.css">
</head>
<body>
<?php
$nameErr = $addErr = $phoneErr = $scake = $flavorcake = $fill = "";
$name = $address = $phone = $rcake = $fillr = $cakeflavor = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addErr = "Email is required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "Gender is required";
} else {
$phone = test_input($_POST["phone"]);
}
if(isset($_POST['SelectedCake'])){
$x=$_POST['SelectedCake'];
}
if(isset($_POST['CakeFlavor'])){
$y=$_POST['CakeFlavor'];
}
if(isset($_POST['Filling'])){
$z=$_POST['Filling'];
}
if(empty($x)){
$scake='Select one Cake';
}else{
$rcake= $x;
}
if(empty($y) OR $y == 'Flavor'){
$flavorcake='Select one flavor';
}else{
$cakeflavor= $y;
}
if(empty($z)){
$fill='Select at least one Fillings';
}else{
foreach($z as $item){
$fillr=$item;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrap">
<div class="cont_order">
<fieldset>
<legend>Make your own Cake</legend>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h4>Select size for the Cake:</h4>
<input type="radio" name="SelectedCake" value="Round6">Round cake 6" - serves 8 people</br>
<input type="radio" name="SelectedCake" value="Round8">Round cake 8" - serves 12 people</br>
<input type="radio" name="SelectedCake" value="Round10">Round cake 10" - serves 16 people</br>
<input type="radio" name="SelectedCake" value="Round12">Round cake 12" - serves 30 people</br>
<span class="error">*<?php echo $scake;?></span>
<h4>Select a Cake Flavor: </h4>
<select name="CakeFlavor">
<option value="Flavor" selected="selected">Select Flavor</option>
<option value="Carrot" >Carrot</option>
<option value="Chocolate" >Chocolate</option>
<option value="Banana" >Banana</option>
<option value="Red Velvet" >Red Velvet</option>
<option value="Strawberry" >Strawberry</option>
<option value="Vanilla" >Vanilla</option>
<option value="Combo" >Combo</option>
</select>
<span class="error">*<?php echo $flavorcake;?></span>
<h4>Select Fillings:</h4>
<label><input type="checkbox" name="Filling[]" value="Cream"/>Cream</label><br>
<label><input type="checkbox" name="Filling[]" value="Fudge"/>Fudge</label><br>
<label><input type="checkbox" name="Filling[]" value="Ganache"/>Ganache</label><br>
<label><input type="checkbox" name="Filling[]" value="Hazelnut"/>Hazelnut</label><br>
<label><input type="checkbox" name="Filling[]" value="Mousse"/>Mousse</label><br>
<label><input type="checkbox" name="Filling[]" value="Pudding"/>Pudding</label><br>
<span class="error">*<?php echo $fill;?></span>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Contact Details</legend>
<label for="name">Name</label><br>
<input type="text" name="name" id="name"><span class="error">*<?php echo $nameErr;?></span>
<br>
<label for="address">Address</label><br>
<input type="text" name="address" id="address"><span class="error">*<?php echo $addErr;?></span>
<br>
<label for="phonenumber">Phone Number</label><br>
<input type="text" name="phone" id="phone"><span class="error">*<?php echo $phoneErr;?></span><br>
</fieldset>
<input type="submit" name="submitted" id="submit" value="Submit"/>
</div>
</form>
<div class="cont_order">
<?php
echo $name.'<br>';
echo $address.'<br>';
echo $phone.'<br>';
echo $rcake.'<br>';
echo $cakeflavor.'<br>';
echo $fillr.'<br>';
?>
</div>
</div>
</body>
</html>
You can do this:
var_dump($_POST['Filling']);
Or just this:
<?php
if(!empty($_POST['Filling'])) {
foreach($_POST['Filling'] as $check) {
echo $check;
}
}
?>
Tell me if it works =)
Fact is, you accept a list for filling.
In your code you do this :
foreach($z as $item){
$fillr=$item;
}
Replace it by :
$fillr = '';
foreach($z as $item){
$fillr .= '- ' . $item . '<br/>';
}
It should work better.
For comment :
#so let's say $z is an array :
$z = [1,2,3,4];
#then you say, for each element of the array as you will call $item, I do something
foreach($z as $item){
$fillr=$item; #here you say : for each element of $z (1,2,3,4), I put this value into $fillr.
}
#so let's do the loop together.
# First pass, $item == 1, so $fillr == 1.
# Second pass, $item == 2, so $fillr == 2.
# ...
# Last pass, $item == 4, so $fillr == 4.
# so then when you show $fillr it's the last item of the list (here 4).
# using PHP, .= means concatenate.
# for instance :
$a = "hello ";
$a .= "world";
echo $a;
> hello world
So basically, what I'm doing is :
Having an empty string I'll call $fillr.
For every element of the list,
Append "the_element plus a <br/>" to $fillr
so then when you output $fillr it looks sexy.
Do you get it bud?

PHP sticky forms dropdown and checkboxes

I'm writing a php form and I can't get the drop down boxes and check boxes to stick as in when I fill in my details but don't click something it will keep everything else filled but that one part that wasn't filled out. I can do it for the input text and radio buttons but I can't get it done for drop downs and checkboxes
<!DOCTYPE html>
<style>
#import url(stickyTextInput.css);
</style>
<?php
if(isset($_REQUEST["left"]))
{
process_form();
}
else
{
display_form_page('');
}
?>
<?php
function display_form_page($error)
{
$self =$_SERVER['PHP_SELF'];
$first_name = isset($_REQUEST['name']) ? $_REQUEST['name']:'';
$last_name = isset($_REQUEST['lastname']) ? $_REQUEST['lastname']:'';
$age = isset($_REQUEST['age']) ? $_REQUEST['age']:'';
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']: '';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head>
<title>
Forms Sticky input
</title>
<style>
#import url(stickyTextInput.css);
</style>
<style type="text/css">
.error
{
color:#ff0000
}
</style>
</head>
<body>
<?php
if($error)
{
echo "<p>$error</p>\n";
}
?>
<form action= "<?php echo $self?>" method = "post">
<h1>Forms-Sticky Input</h1>
<label>First Name:</label>
<input type="text" size="10" maxlength="40" name="name" value = "<?php echo $first_name?>">
<br>
<label>Last Name:</label>
<input type="text" size="10" maxlength="40" name="lastname" value = "<?php echo $last_name?>">
<br>
<label>Age:</label>
<input type="text" name="age" size="10" value="<?php echo $age?>">
<br>
<label>Gender</label>
<input type="radio" name="gender" value="male" <?php check($gender, "male")?>>Male
<input type="radio" name="gender" value="female" <?php check ($gender, "female")?>>Female
<br>
<label>Select favourite Colour</label>
<select name= "color">
<option <?php checkradio($color, "Red")?>>Red
<option <?php checkradio($color, "Blue")?>>Blue
<option <?php checkradio($color, "Green")?>>Green
<option <?php checkradio($color, "Pink")?>>Pink
<option selected="selected" disabled="disabled">
</select>
<br>
<label>Food</label>
<input type="checkbox" name="food[]" value="beans" <?php checkbox ($food, "beans")?>>Beans
<input type="checkbox" name="food[]" value="crisps" <?php checkbox ($food, "crisps")?>>Crisps
<input type="checkbox" name="food[]" value="lemons" <?php checkbox ($food, "lemons")?>>Lemons
<br>
<div id="buttons">
<input type="submit" name="left" id="left" value="Submit" >
<input type="reset" name="right" id="right" value="Reset" >
</div>
</form>
</body>
</html>
<?php
}
?>
<?php
// If $group has the value $val then select this list item
function check($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function checkradio($group, $val)
{
if ($group === $val)
{
echo 'selected = "selected"';
}
}
?>
<?php
// If $group has the value $val then select this list item
function checkbox($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function process_form()
{
$error = validate_form();
if($error)
{
display_form_page($error);
}
else
{
display_output_page();
}
}
?>
<?php
function validate_form()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
$error = '';
$reg_exp = '/^[a-zA-Z\-\']+$/';
$reg_exp1 = '[0-9]{3}';
if(!preg_match($reg_exp, $first_name))
{
$error .= "<span class=\"error\">First Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!preg_match($reg_exp, $last_name))
{
$error .= "<span class=\"error\">Last Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!is_numeric($age))
{
$error .= "<span class=\"error\">Age is invalid (numbers only)</span><br>";
}
if (strlen($gender) == 0)
{
$error .= "<span class=\"error\">Select Male/Female</span><br>";
}
if (strlen($color) == 0)
{
$error .= "<span class=\"error\">Select one color</span><br>";
}
if (! is_array($food))
{
$error .= "<span class=\"error\">You must select one food</span><br>";
}
return $error;
}
?>
<?php
function display_output_page()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head><title>Form Results</title></head>
<body>
<h1>Form Results</h1>
<?php
echo " First Name: $first_name<br/>\n";
echo " Last Name: $last_name<br/>\n";
echo " Age: $age<br/>\n";
echo " Gender: $gender<br/>\n";
echo " Favourite Color: $color<br/>\n";
echo "<ul>";
if (is_array($food))
{
echo "Favourite Food is:";
foreach($food as $selection)
{
echo "<li>$selection</li>";
}
}
echo "</ul>";
?>
</body>
</html>
<?php
}
?>
Possibly a browser issue, however most browsers only require 'checked' at the end of the html input element for checkboxes. However you appear to be outputting checked = "checked" This is possibly the problem. Have a look at the sample below:
<?php
$name = isset($_GET['name']) ? $_GET['name'] : '';
$agree = isset($_GET['agree']) ? 'checked' : '';
$title = isset($_GET['title']) ? $_GET['title'] : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="name" id="name" value="<?=$name;?>">
<input type="checkbox" name="agree" id="agree" <?=$agree;?>>
<select name="title" id="title">
<option value="Mr" <?=$title == 'Mr' ? 'selected' : ''?>>Mr</option>
<option value="Mrs" <?=$title == 'Mrs' ? 'selected' : ''?>>Mrs</option>
<option value="Miss" <?=$title == 'Miss' ? 'selected' : ''?>>Miss</option>
</select>
<button type="submit">submit</button>
</form>
</body>
</html>
After processing the values the output html should be as follows:
<form action="">
<input type="text" name="name" id="name" value="test">
<input type="checkbox" name="agree" id="agree" checked>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss" selected>Miss</option>
</select>
<button type="submit">submit</button>
</form>

Categories