PHP sticky forms dropdown and checkboxes - php

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>

Related

Unit Converter PHP

I am struggling to get my PHP unit converter to work.
I am trying to get multiple converters going but cant seem to get it working.
It'd be great if someone could show me where I'm going wrong and help me get it going. :)
<?php
if($_POST){
$fahrenheit = $_POST['fahrenheit'];
$celsius = ($fahrenheit - 32)*5/9;
}
if($_POST){
$celsius = $_POST['celcius'];
$fahrenheit = ($celcius - 32)*5/9;
}
?>
<form action="" method="post">
Fahrenheit: <input type="text" name="fahrenheit" /><br />
<?php
if(isset($celsius)){
echo "Celsius = ".$celsius;
}
?>
</form>
<?php
function fahrenheit_to_celsius($given_value)
{
$celsius=5/9*($given_value-32);
return $celsius ;
}
function celsius_to_fahrenheit($given_value)
{
$fahrenheit=$given_value*9/5+32;
return $fahrenheit ;
}
function inches_to_centimeter($given_value)
{
$centimeter=$given_value/2.54;
return $centimeter ;
}
function centimeter_to_inches($given_value)
{
$inches=$given_value*2.54
}
?>
<html>
<head>
<title>Temp. Conv.</title>
</head>
<body>
<form action="" method="post">
<table>
<!-- FAHRENHEIGHT & CELCIUS V -->
<tr>
<td>
<select name="first_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="btn" value="Convert">
</td>
</tr>
<!--FAHRENHEIGHT & CELCIUS ^ -->
<!-- CENTEMETERS & INCHES -->
<tr>
<td>
<select name="first_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<!--CENTEMETERS & INCHES ^-->
<tr>
<td>
<?php
if(isset($_POST['btn']))
{
$first_temp_type_name=$_POST['first_temp_type_name'];
$second_temp_type_name=$_POST['second_temp_type_name'];
$given_value=$_POST['given_value'];
if($first_temp_type_name=='fahrenheit')
{
$celsious=fahrenheit_to_celsius($given_value);
echo "Fahrenheit $given_value = $celsious Celsious";
}
if($first_temp_type_name=='celsius')
{
$fahrenheit=celsius_to_fahrenheit($given_value);
echo "Celsious $given_value = $fahrenheit Fahrenheit";
}
}
if(isset($_POST['btn']))
{
$first_length_type_name=$_POST['first_length_type_name'];
$second_length_type_name=$_POST['second_length_type_name'];
$given_value=$_POST['given_value'];
if($first_length_type_name=='centimeter')
{
$centimeter=centimeter_to_inches($given_value);
echo "Centimeter $given_value = $inches Inches";
}
if($first_length_type_name=='inches')
{
$centimeter=inches_to_centimeter($given_value);
echo "Inches $given_value = $centimeter centimeter";
}
}
?>
</td>
</tr>
</table>
</form>
</body>
</html>
I know there is a lot going on, my apologies.
Any help is greatly appreciated :)
Hi please use the following code.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$convertedTemperature = 0;
/* The condition is entered when the request is of POST type. */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$temperature = $_POST['temperature'];
$fromConvertionUnit = $_POST['fromConvertionUnit'];
$toConvertionUnit = $_POST['toConvertionUnit'];
/* if the temperature conversion are of same unit then no need for conversion */
if($fromConvertionUnit == $toConvertionUnit){
$convertedTemperature = $temperature;
}else if($fromConvertionUnit == 'fahrenheit' && $toConvertionUnit == 'celcius') {
/* formula to convert Fahrenheit to Celcius */
$convertedTemperature = ($temperature - 32) * 0.5556;
}else if($fromConvertionUnit == 'celcius' && $toConvertionUnit == 'fahrenheit') {
/* formula to convert Celcius to Fahrenheit */
$convertedTemperature = ($temperature * 1.8) + 32;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temperature Converter</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div>
<!-- If the temperature value has be submitted and has data then it will prefilled -->
<label for="temperature">Temperature</label> <br/>
<input type="number" name="temperature" id="temperature" value="<?php echo (!empty($temperature)) ? $temperature : '' ?>">
</div>
<div>
<label for="fromConvertionUnit">Select From Convertion Unit</label><br/>
<select name="fromConvertionUnit" id="fromConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<div>
<label for="toConvertionUnit">Select To Convertion Unit</label><br/>
<select name="toConvertionUnit" id="toConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<!-- Once the page is submitted and conversion is done the respective values will be added in the following section -->
<div>
Converted Temperature <b> <?php echo (!empty($temperature)) ? $temperature : '--' ?></b> Value From <b><?php echo (!empty($fromConvertionUnit)) ? $fromConvertionUnit : '--' ?></b> TO <b><?php echo (!empty($toConvertionUnit)) ? $toConvertionUnit : '--' ?></b> is <b><?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '--' ?><b/>
<label for="converted_value">Converted Value</label><br/>
<input type="number" value="<?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '0' ?>">
</div>
<div>
<input type="submit" value="Convert">
</div>
</form>
</body>
</html>
If you want to make a converter, all you need is one input - and a dropdown between what you wish to convert to. Then use a switch in PHP when the form was submitted to check what function you wish to use.
Your current issue is that you overwrite a lot of values, and that you don't check for the right buttons. This is also over-complicating it.
You can further develop this converter by making sure that the input is an actual number - by using filter_var() with a flag that's suitable for your need. You can either validate it or sanitize it, see FILTER_SANITIZE vs FILTER VALIDATE, whats the difference - and which to use?.
<?php
if (isset($_POST['submit'])) {
switch ($_POST['convert']) {
case "cm-in":
$result = centimeter_to_inches($_POST['value']);
$old_unit = 'cm';
$new_unit = ' inches';
break;
case "in-cm":
$result = inches_to_centimeter($_POST['value']);
$old_unit = ' inches';
$new_unit = 'cm';
break;
case "f-c":
$result = fahrenheit_to_celsius($_POST['value']);
$old_unit = ' Farenheit';
$new_unit = ' Celcius';
break;
case "c-f":
$result = celsius_to_fahrenheit($_POST['value']);
$old_unit = ' Celcius';
$new_unit = ' Farenheit';
break;
}
}
function fahrenheit_to_celsius($given_value) {
return 5/9*($given_value-32);
}
function celsius_to_fahrenheit($given_value) {
return $given_value*9/5+32;
}
function inches_to_centimeter($given_value) {
return $given_value/2.54;
}
function centimeter_to_inches($given_value) {
return $given_value*2.54;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Conversions</title>
</head>
<body>
<form method="post">
Convert <input type="text" name="value" /><br />
<select name="convert">
<option value="">--Select one--</option>
<optgroup label="Units of Length">
<option value="cm-in">Centimeter to inches</option>
<option value="in-cm">Inches to centimeter</option>
</optgroup>
<optgroup label="Units of Temperature">
<option value="f-c">Farenheit to Celcius</option>
<option value="c-f">Celcius to Farenheit</option>
</optgroup>
</select>
<input type="submit" name="submit" value="Convert" />
</form>
<?php
if (!empty($result))
echo '<p>'.$_POST['value'].$old_unit.' equals '.$result.$new_unit.'</p>';
?>
</body>
</html>

Getting empty $_FILES array

I want to upload a file to server.I have added all the code to upload file to server but the $_FILES array is empty. File Value is not getting set in an array.
I have done same code for another web page and it works fine, but not getting whats the issue in this.
I have set the enctype as multipart/form-data but still its giving empty array.
html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<script>
</script>
<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<select id="types" name="types" onchange="myFunction(this)">
<option value="">Select type</option>
<option value="2">Add Link</option>
<option value="0">Upload Image</option>
<option value="1">Upload Video</option>
</select><br><br>
<div id="link" style="display: none">
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>
<p>
<label for="urlType">Select Url Type :(required)</label>
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<!-- <option value="0">Server Image</option>
<option value="1">Server Video</option>-->
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
</div>
<div id="filediv" style="display: none">
Select file to upload:
<br><br>
<input name = "file" type="file" id="fileToUpload"><br><br>
</div>
<p>
<label for="postType"> Select Post Type :(required)</label>
<select name="postType" id="postType">
<option value="">Select Post Type...</option>
<option value="0">Normal</option>
<option value="1">Featured</option>
<option value="2">Sponsored</option>
</select>
</p>
<p>
<label for="category"> Select Category :(required)</label>
<select name="category" id="category">
<option value="">Select Category...</option>
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<!-- Cancel
Add User-->
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</fieldset>
<div class="result" id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script>
function myFunction(obj) {
var type = obj.value;
var x = document.getElementById('link');
var y = document.getElementById('filediv');
if(type == "2")
{
x.style.display = 'block';
y.style.display = 'none';
}
else {
x.style.display = 'none';
y.style.display = 'block';
}
}
</script>
</form>
</body>
</html>
addPost.php
<?php
include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {
if($_POST['action_type'] == 'add') {
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare("insert into keywords(keyword)
values(?)");
$stmt->execute(array($_POST['keywords']));
$file_result = "";
if(strcmp($_POST['types'],"2") == 0)
{
//insert data into posts table
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
echo "Post submitted.";
} else {
echo "Could not submit post.";
}
}
else {
if(isset($_POST['submit'])){
print_r($_FILES);
if (isset($_FILES["file"]["name"])) {
$file_result = "";
if ($_FILES["file"]["error"] > 0) {
$file_result .= "No file uploaded or invalid file.";
$file_result .= "Error code : " . $_FILES["file"]["error"] . "<br>";
} else {
if (strcmp($_POST['types'], "0") == 0) {
$target_dir = "AgTv/images/";
} else {
$target_dir = "AgTv/videos/";
}
$newfilename = preg_replace('/\s+/', '',
$_FILES["file"]["name"]);
$target_file = $target_dir . basename($newfilename);
/*$target_file = $target_dir . basename($_FILES["file"]["name"]);*/
$file_result .=
"Upload " . $_FILES["file"]["name"] . "<br>" .
"type " . $_FILES["file"]["type"] . "<br>" .
"temp file " . $_FILES["file"]["tmp_name"] . "<br>";
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $newfilename, $_POST['types'], $_POST['desc'], $_POST['keywords'], $_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
echo "The file " . basename($_FILES['file']['name']) . " has been uploaded, and your information has been added to the directory";
} else {
echo "Could not submit post.";
}
}
}
}
else{
echo 'empty file';
}
}
}
}
}
?>
Can anyone help please? Thank you.
UPDATED WITH SOLUTION:
just add
<script>
$("#postForm").validate();
</script>
below the inclusion of jquery.validate.min.js. You $_FILES array is working fine, you are just not sending the post at all!

How to display selected value in combo box in php?

I've written this code... but this fails to display text... not sure what's wrong with the code. I'm new to PHP and trying to create a page that gets customer details and puts it in SQL.
<!DOCTYPE html>
<html>
<body>
<?php
$initial="";
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit"></form>
<br>
<br>
<?php
echo "Customer Intial: $initial <br>";
?>
</body>
</html>
Try this:
$initial="";
if(isset($_POST['initial'])){
$initial=htmlentities($_POST['initial']);
}
You correctly sent the POST however you didn't put the value given with the POST into the $initial variable.
<!DOCTYPE html>
<html>
<body>
<?php
$initial = "";
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit"></form>
<br>
<br>
<?php
$initial = filter_input(INPUT_POST, "initial");//GET the input in post method
if ($initial == 1) {
$initial_value = "Mr.";
} elseif ($initial == 2) {
$initial_value = "Mrs.";
} elseif ($initial == 3) {
$initial_value = "Ms.";
} elseif ($initial == 4) {
$initial_value = "M/s";
} else {
$initial_value = "Select initial";
}
echo "Customer Intial: $initial_value <br>";
?>
</body>
</html>
Try,
<form method="post" action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>>
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<br>
<br>
<?php
if(isset($_POST['initial'])){
$initial=$_POST['initial'];
} else {
$initial = "empty";
}
echo "Customer Intial : ".$initial;
?>
</body>
</html>

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?

Multiple Form Dropdown Form, Validation, PHP

I have this whole code. Jumbled but what I'm trying to do is to have a drop down menu with selections from 1 -10. Then after selecting one, would spit out another form so that if there 3 were selected, would show three rows of fields (name, email). Validation included. What I was first "hard coded" on how many rows of fields to spit out but now what I wanted to do is to have a "selection" in dropdown menu so that the user has the ability to select.... Seem to work but doesn't process. Any PHP expert help? No db, no client-base, no smart alec. If you have time to help please do.
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
// Check if the form has been submitted:
if (isset($_POST['submit'])) {
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1) ) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i+1;
echo $row.": ".$_POST['firstname'][$i]." ".$_POST['lastname'][$i].", ".$_POST['email'][$i]." <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#",$_POST['firstname'][$i],$body);
$body = str_replace("#lastname#",$_POST['lastname'][$i],$body);
$body = str_replace("#email#",$_POST['email'][$i],$body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<? echo $i.': '; ?><input type="text" name="firstname[]" size="20" value="<?php if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="lastname[]" size="20" value="<?php if (isset($_POST['lastname'] [$i])) { print htmlspecialchars($_POST['lastname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?><input type="text" name="email[]" size="20" value="<?php if (isset($_POST['email'][$i])) { print htmlspecialchars($_POST['email'][$i]); } ?>" />
</td>
</tr>
<?php } ?>
<tr><td><p><input type="submit" class="button" name="submit" value="Register!" /></td>
</tr>
</table>
</form>
<?php
}
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>
You have to move the second form submit code outside of first form submit. Try this
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
$problem = false; //always try to initialize variables, you may not run into unexpected warnings and problems.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<? echo $i . ': '; ?><input type="text" name="firstname[]" size="20"
value="<?php if (isset($_POST['firstname'][$i])) {
print htmlspecialchars($_POST['firstname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<input type="text" name="lastname[]" size="20"
value="<?php if (isset($_POST['lastname'] [$i])) {
print htmlspecialchars($_POST['lastname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?><input type="text" name="email[]" size="20"
value="<?php if (isset($_POST['email'][$i])) {
print htmlspecialchars($_POST['email'][$i]);
} ?>"/>
</td>
</tr>
<?php } ?>
<tr>
<td><p><input type="submit" class="button" name="submit" value="Register!"/></td>
</tr>
</table>
</form>
<?php
} // moved second for submit to here
elseif (isset($_POST['submit'])) { // Check if the form has been submitted:
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1)) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i + 1;
echo $row . ": " . $_POST['firstname'][$i] . " " . $_POST['lastname'][$i] . ", " . $_POST['email'][$i] . " <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#", $_POST['firstname'][$i], $body);
$body = str_replace("#lastname#", $_POST['lastname'][$i], $body);
$body = str_replace("#email#", $_POST['email'][$i], $body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>

Categories