I have a multiple select on my code, what I need to do is to have a validation when the user click the submit button without selecting any of the given list.
Here's the sample code:
index.php
<?php
IF(isset($_POST['Rtype'])){
$RetrieveType = $_POST['Rtype'];
IF($RetrieveType == 'date_range'){
$start_date = new DateTime($_POST['start_date']);
$sd = date_format($start_date,'Y-m-d');
$p_week=array();
$m_month=01;
$end_date = new DateTime($_POST['end_date']);
$end_date-> add(new DateInterval('P1D'));
$ed =date_format($end_date,'Y-m-d');
}
ELSEIF($RetrieveType == 'weekly'){
$p_week = $_POST['week'];
$m_week = implode(',',$p_week);
$m_month =$_POST['month_m'];
$m_year =$_POST['year_m'];
$p_lob = $_POST['lob'];
$sc_lob=implode(',',$p_lob);
} ELSE
{
$RetrieveType = 'date_range';
$sd = date('Y-m-01');
$start_date = date('Y-m-01');
$ed = date('Y-m-d');
$end_date = date('Y-m-d');
$m_month=date ('m');
$p_week=array();
$m_year= date ('Y');
$sc_lob='';
}
?>
<html>
<head>
<head>
<body>
<form action="index.php" method="POST" class="form-inline">
<label for="sel1">Week:</label>
<select data-placeholder="<?php echo (isset($_POST['week']) ? "Week/s Currently Selected: ".implode(",",$_POST['week']) : "Select Week"); ?>"
class="chosen-select" multiple tabindex="4" style="width:350px;" name= "week[]">
<option value="1" id="empty">Week 1</option>
<option value="2" id="empty">Week 2</option>
<option value="3" id="empty">Week 3</option>
<option value="4" id="empty">Week 4</option>
<option value="5" id="empty">Week 5</option>
</select>
<label for="sel1">LOB:</label>
<select data-placeholder="<?php echo (isset($_POST['lob']) ? "LOB/s Currently Selected: ".implode(",",$_POST['lob']) : "Select LOB"); ?>"
class="chosen-select" multiple tabindex="4" style="width:350px;" name= "lob[]">
<?php
$lob = array();
$q = "SELECT distinct LOB from roster where EmployStatus='active' and SDLead <> '' group by LOB";
$params = array();
$query = sqlsrv_query($conn, $q);
while($rowsss= sqlsrv_fetch_array($query)) {
$lob = $rowsss['LOB'];
echo "<option value='".$lob."'>".$lob."</option>";
}
for ($i = 0; $i <= count($lob) - 1; $i++) {
IF($sc_lob == $lob[$i])
{$isSelected = 'selected';}
elseif(1==1)
{$isSelected='';}
echo "<option ".$isSelected." value='".$lob[$i]."'>".$lob[$i]."</option>"; }
?>
<input type="hidden" name="Rtype" value="weekly">
<input class="btn btn-primary" type="submit" />
</form>
What I wanted to achieve is when the user clicked the submit button without selecting any on the "Week" list or "LOB" list, there would be an error message that says "This field is required, select at least one.". Actually I already did this before, when I'm just using a checkbox. I placed the code below after the label tag:
sample code:
<?php
if(isset($_GET['err']))
{
$err = $_GET['err'];
if($err == 1)
{
echo "<span class='text-danger'>* This field is required, select at least one.</span>";
}
else
{
echo "";
}
}
else
{
echo "";
}
?>
Try this
if(isset($_POST['submit']){
errors = 0;
if($_POST['nameOfSelect'] == ""){
errors++;
}
if(errors == 0){
return true;
}else{
return false;
}
Related
I have this onchange event on php, if the user choose an option, it fetched the data that is connected on it. However, the page refreshes and the choice of the user disappear. Also, I cannot insert the data to database. I've tried add a form method="post" to the form attribute, but unfortunately it cannot fetch the data.
Thankyou in advance.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$gradeassign = '';
$sectionassign = '';
function getPosts()
{
$posts = array();
$posts[3] = $_POST['sectionassign'];
$posts[4] = $_POST['gradeassign'];
return $posts;
}
if(isset($_POST['addfac']))
{
$data = getPosts();
$insertStmt = $con->prepare('INSERT INTO
facultyagain(sectionnumber,gradelevelassign)
VALUES(:sectionassign,:gradeassign)');
$insertStmt->execute(array(
':sectionassign'=> $data[3],
':gradeassign'=> $data[4],
));
if($insertStmt)
{
echo 'Data Inserted';
}
}
?>
<html>
<head>
<title>Country</title>
</head>
<body>
<form action="trial.php">
Select Your grade
<select name="gradeassign" onchange="this.form.submit()">
<option value="" disabled selected>--select--</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="europe">Europe</option>
</select>
<?php
require 'connection.php';
if(isset($_GET["gradeassign"])){
$gradeassign=$_GET["gradeassign"];
$sql = "SELECT sectionassign FROM sections WHERE gradeassign='$gradeassign'";
$result = $con->query($sql);
echo "<select>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='$row[sectionassign]'>" . $row["sectionassign"]. " </option>";
}
} else { echo "<B>0 Results</B>"; }
echo "</select>";
}
?>
<BR>
<button id="addfac" name="addfac">Add Faculty</button>
</form>
</body>
</html>
You can also store the value in a variable and check to see if the option matches the variable. For example:
<option value="" disabled>--select--</option>
<option value="1" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "1") echo "checked"; ?>>Grade 1</option>
<option value="2" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "2") echo "checked"; ?>>Grade 2</option>
<option value="europe" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "europe") echo "checked"; ?>>Europe</option>
The better way to do it would be to create the whole list with a loop. Bu this should work.
I am trying to add a dropdown list to an RSS feed parser.
I have this:
<fieldset class="rsslib">
<?php
$cachename = "rss-cache-tmp.php";
$url = "http://www.theweekinchess.com/twic-rss-feed";
if(file_exists($cachename))
{
$now = date("G");
$time = date("G", filemtime($cachename));
if($time == $now)
{
include($cachename);
exit();
}
}
require_once("rsslib.php");
$cache = RSS_Display($url, 15, false, true);
file_put_contents($cachename, $cache);
echo $cache;
?>
</fieldset>
But I want to to set the $url in php with a select option like so:
<?php
$temp = $_POST["url"];
?>
<form method = "post">
<select name="url" id="url">
<option value="http://www.theweekinchess.com/twic-rss-feed">TWIC</option>
<option value="http://chesscafe.com/feed/">Chess Cafe</option>
<option value="http://www.chessdom.com/rss">Chessdom</option>
<option value="http://chess-news.ru/rss-eng">Chess-news</option>
<option value="http://www.chess.com/rss/articles">chess.com</option>
</select>
</form>
But I can't pass the form variable to the php script. I tried but my results were pathetic and I wanted to leave the original code to simplify things.
Any ideas?
Your form needs an action.
You need to know if the form was submitted: ($sub)
<?php
$sub = intval( $_POST["sub"]);
if ($sub == 1){
$url= $_POST["url"];
}
else{
$url = "http://www.theweekinchess.com/twic-rss-feed";
}
require_once("rsslib.php");
$cache = RSS_Display($url, 15, false, true);
$cachename = "rss-cache-tmp.php";
file_put_contents($cachename, $cache);
// I have no idea what you are doing here or why
if(file_exists($cachename)){
$now = date("G");
$time = date("G", filemtime($cachename));
if($time == $now){
include($cachename);
exit();
}
}
echo <<<EOT
$cache;
<fieldset class="rsslib"> // ??????
</fieldset>
<form action="#" method = "post">
<input type="hidden" name="sub" value="1" />
<select name="url" id="url">
<option value="http://www.theweekinchess.com/twic-rss-feed">TWIC</option>
<option value="http://chesscafe.com/feed/">Chess Cafe</option>
<option value="http://www.chessdom.com/rss">Chessdom</option>
<option value="http://chess-news.ru/rss-eng">Chess-news</option>
<option value="http://www.chess.com/rss/articles">chess.com</option>
</select>
</form>
EOT;
?>
I'm making a website for a friend and basically I have 15 fields that are editable depending on the user type. Basically my code is echoing the row out on to the field, but when when I go to change it and update the database nothing happens. I don't receive any error messages, so i'm thinking it's something to do with my condition statements. My functions work fine, how ever my query doesn't seem to like me.
<?php
//end of function
}
// connect to the database
$server = 'localhost';
$user = 'root';
$pass = '';
$database = 'bubbles';
//Connect to the database
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
//Select the database name
$select = mysql_select_db($database) or die ("Could not connect to database ... \n" . mysql_error ());
// check if the form has been submitted. If it has, process the form and save it to the database
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
//Get form data to make sure it's valid
$id = $_POST["id"];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$dueDate = mysql_real_escape_string(htmlspecialchars($_POST['dueDate']));
$numOfPages = mysql_real_escape_string(htmlspecialchars($_POST['numOfPages']));
$numOfCopies = mysql_real_escape_string(htmlspecialchars($_POST['numOfCopies']));
$paperSize = mysql_real_escape_string(htmlspecialchars($_POST['paperSize']));
$paperColor = mysql_real_escape_string(htmlspecialchars($_POST['paperColor']));
$weight = mysql_real_escape_string(htmlspecialchars($_POST['weight']));
$finishing = mysql_real_escape_string(htmlspecialchars($_POST['finishing']));
$paymentMethod = mysql_real_escape_string(htmlspecialchars($_POST['paymentMethod']));
$printColor = mysql_real_escape_string(htmlspecialchars($_POST['printColor']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
$comment = mysql_real_escape_string(htmlspecialchars($_POST['comment']));
// check that firstname/lastname fields are both filled in
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
{
// generate error message
$error = 'Please fill in all required fields!';
//error, display form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
$error);
}
else
{
//Insert form data into the database or die if there is an error
print $sql;
$sql = ("UPDATE orders SET `name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."' WHERE id = '".$id."'");
$result = mysql_query($sql) or die (mysql_error());
// once saved, redirect back to the view page
header("Location: http://localhost/Bubbles/view-orders.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
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM orders 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
$id = $row['id'];
$name = $row['name'];
$dueDate = $row['due_date'];
$numOfPages = $row['numOfPages'];
$numOfCopies = $row['numOfCopies'];
$paperSize = $row['paper_size'];
$paperColor = $row['paper_color'];
$weight = $row['weight'];
$finishing = $row['finishing'];
$paymentMethod = $row['payment_method'];
$printColor = $row['color'];
$status = $row['status'];
$comment = $row['comments'];
// show form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
'');
}
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!';
}
}
?>
Updated with HTML
<html>
<head>
</head>
<body>
<form action"" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="floatLeft">
<p>Name: <br /> <input type="text" name="name" value="<?php echo $name; ?>"/></p>
<p>Due Date (ex: yyyy-mm-dd): <br /> <input type="datetime" name="dueDate" value="<?php echo $dueDate; ?>" /></p>
<p># of Pages <br /> <input type="number" name="numOfPages" value="<?php echo $numOfPages; ?>"/></p>
<p># of Copies <br /> <input type="number" name="numOfCopies" value="<?php echo $numOfCopies; ?>"/></p>
</div>
<div class="floatLeft">
<p>Paper Size<br />
<select name = "paperSize" value="<?php echo $paperSize; ?>">
<option value="8.5 x 11in">8.5 x 11 inches</option>
<option value="8.5 x 14in">8.5 x 14 inches</option>
<option value="11 x 17in">11 x 17 inches</option>
</select>
</p>
<p>Paper Color<br />
<select name = "paperColor" value="<?php echo $paperColor; ?>">
<option value = "pulsar pink">Pulsar Pink</option>
<option value = "fireball fuchsia">Fireball Fuchsia</option>
<option value = "plasma pink">Plasma Pink</option>
<option value = "re-entry red">Re-entry Red</option>
<option value = "rocket red">Rocket Red</option>
<option value = "cosmic orange">Cosmic Orange</option>
<option value = "galaxy gold">Galaxy Gold</option>
<option value = "solar yellow">Solar Yellow</option>
<option value = "venus violet">Venus Violet</option>
<option value = "planetary purple">Planetary Purple</option>
<option value = "celestial blue">Celestial Blue</option>
<option value = "lunar blue">Lunar Blue</option>
<option value = "gamma green">Gamma Green</option>
<option value = "martian green">Martian Green</option>
<option value = "terra green">Terra Green</option>
<option value = "lift-off lemmon">Lift-off Lemon</option>
</select>
</p>
<p>Weight<br/>
<select name = "weight" value="<?php echo $weight; ?>">
<option value="20lbs">20lbs</option>
<option value="60lbs">60lbs</option>
<option value="65lbs">65lbs</option>
</select>
</p>
<p>Finishing<br />
<select name = "finishing" value="<?php echo $finishing; ?>">
<option value="none">None</option>
<option value="cutting">Cutting</option>
<option value="folding">Folding</option>
<option value="quaters">Quaters</option>
<option value="binding">Bindings</option>
</select>
</p>
<p>Payment method<br />
<select name = "paymentMethod" value="<?php echo $paymentMethod; ?>">
<option value="Cash">Cash</option>
<option value="Credit">Credit</option>
<option value="Check">Check</option>
<option value="Wilscard">Wilscard</option>
</select>
</p>
<p>Print BW/C<br />
<select name = "printColor" value="<?php echo $printColor; ?>">
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Color">Color</option>
</select>
</p>
</p>
</div>
<div class="floatLeft">
<p>Status<br />
<select name = "status" value="<?php echo $row['status']; ?>">
<option value="Recieved">Received</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
<p>Comment (Cannot exceed 200 characters):<br />
<textarea name="comment" value="<?php echo $comment; ?>"></textarea><br />
</p>
<input type="submit" value="Edit Order" />
</div>
</body>
</html>
UPDATE: I fixed the code, thanks everyone for all the help, but my error was that when I check the empty field, there was nothing written in the comment box so it was thinking all fields were empty when in reality they weren't. i updated the field check with this code and it works fine now.
I updated the if statement from this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
To this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '')
It doesn't look like you're running the query after you create it in the $sql variable. You'll want to execute the query like you do later in the code:
$result = mysql_query($sql) or die(mysql_error());
This will return true on success or false (and die) on failure.
If you execute your UPDATE sql statement should give you some ERROR (since you forgot SET). However, you are not executing it. Once you fix that issue, you need to change your UPDATE statement to
$sql = "UPDATE orders
SET
`name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."'
WHERE
id = '".$id."'";
Reference: https://dev.mysql.com/doc/refman/5.0/en/update.html
Note: I escaped name and status columns since their are reserved words
Use this query it may solve your problem:
$sql = "UPDATE orders set name ='".$name."' set due_date = '".$dueDate."' set numOfPages = '".$numOfPages."' set numOfCopies = '".$numOfCopies."' set paper_size = '".$paperSize."' set paper_color = '".$paperColor."' set weight = '".$weight."' set finishing = '".$finishing."' set payment_method = '".$paymentMethod."' set color = '".$printColor."' set comments = '".$comment."' set status = '".$status."' WHERE id = '".$id."' ";
I got this code but it is not inserting the content of the option (textarea) into the database.
connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "copy";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$db);
?>
submit.php
<?php
include 'connection.php';
$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];
if(!$_POST['submit']) {
echo "please fill out the form";
header('Location: select.html');
}
else {
$sql = "INSERT INTO remove(foodA, foodB, foodC, foodD, foodE) VALUES (?,?,?,?,?);";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt,"sssss",$foodA,$foodB,$foodC,$foodD,$foodE);
mysqli_stmt_execute($stmt);
echo "User has been added!";
header('Location: select.html');
}
select.html
<html lang="en">
<title>Catering Service</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/js.1.js" type="text/javascript"></script>
</head>
<body>
<form action="submit.php" method="post">
<select multiple="multiple" class="options" id="textarea" >
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
<button type="button" id="copy" onclick="yourFunction()">Copy</button>
<button type="button" id="remove" onclick="yourFunction()">Remove</button>
<select id="textarea2" multiple class="remove" >
<input type="submit" name="submit" />
</form>
</select>
</html>
You need to name the <select> so you can use the data.
name="food[]"
Like this
<select multiple="multiple" name="food[]" class="options" id="text area" >
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
Then if you want the value to be 0 or 1, depending on selected or not, you can use the following to replace this:
$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];
to
$foodA = 0;
$foodB = 0;
$foodC = 0;
$foodD = 0;
$foodE = 0;
foreach ($_POST['food'] as $value) {
if($value == 'foodA')
$foodA = 1;
if($value == 'foodB')
$foodB = 1;
if($value == 'foodC')
$foodC = 1;
if($value == 'foodD')
$foodD = 1;
if($value == 'foodE')
$foodE = 1;
}
You need to name your select with name=food or something so it will be in $_POST['food']. Each option in the select does not show up in $_POST, only what is selected will be in the name of the select. Each option is not it's own thing.
<select multiple="multiple" name="food" class="options" id="textarea" >
<option value="foodA">foodA</option>
<option value="foodB">foodB</option>
<option value="foodC">foodC</option>
<option value="foodD">foodD</option>
<option value="foodE">foodE</option>
</select>
When you save the data it will have:
$_POST['food'] with the value of 'foodA' if multiples, it will be 'foodA, foodB'
I have started with PHP and HTML and would like to execute simple code with three drop-down lists (select tag). But when I make selection from one, the other two selected values disappear. Should I save values when submitting them and then echo. If yes, how can I do it. Sample code will be appreciated.
<?php // formtest_2.php
$name_vid = $name_type = $name_model = "";
if (isset($_POST['vid']))$name_vid=($_POST['vid']);
else $name_vid="no";
if (isset($_POST['type']))$name_type=sanitizeString($_POST['type']);
else $name_type="no";
if (isset($_POST['model']))$name_model=sanitizeString($_POST['model']);
else $name_model="no";
echo <<<_END
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="" selected>Product</option>
<option value = "apple">apple</option>
<option value = "cherry">cherry</option>
<option value = "orange">orange</option>
</select>
<input type="submit"/><br />
<select name="type" size="1">
<option value="" selected>Color</option>
<option value = "green">green</option>
<option value = "red">red</option>
<option value = "orange">orange</option>
</select>
<input type="submit"/><br />
<select name="model" size="1">
<option value="" selected>Model</option>
<option value = "1-a">1-a</option>
<option value = "2-b">2-b</option>
<option value = "3-c">3-c</option>
</select>
<input type="submit"/><br />
</form>
</body>
</html>
_END;
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I think you need to re-select the values of the drop downs after submission. The following code would be a fix.
<?php // formtest_2.php
$name_vid = $name_type = $name_model = "(nothing)";
if (isset($_POST['vid']) && $_POST['vid']) $name_vid=($_POST['vid']);
if (isset($_POST['type']) && $_POST['type']) $name_type=sanitizeString($_POST['type']);
if (isset($_POST['model']) && $_POST['model']) $name_model=sanitizeString($_POST['model']);
?>
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="">Product</option>
<option value = "apple" <?php if($name_vid == 'apple') echo 'selected="selected"'; ?>>apple</option>
<option value = "cherry" <?php if($name_vid == 'cherry') echo 'selected="selected"'; ?>>cherry</option>
<option value = "orange" <?php if($name_vid == 'orange') echo 'selected="selected"'; ?>>orange</option>
</select>
<br />
<select name="type" size="1">
<option value="">Color</option>
<option value = "green" <?php if($name_type == 'green') echo 'selected="selected"'; ?>>green</option>
<option value = "red" <?php if($name_type == 'red') echo 'selected="selected"'; ?>>red</option>
<option value = "orange" <?php if($name_type == 'orange') echo 'selected="selected"'; ?>>orange</option>
</select>
<br />
<select name="model" size="1">
<option value="">Model</option>
<option value = "1-a" <?php if($name_model == '1-a') echo 'selected="selected"'; ?>>1-a</option>
<option value = "2-b" <?php if($name_model == '2-b') echo 'selected="selected"'; ?>>2-b</option>
<option value = "3-c" <?php if($name_model == '3-c') echo 'selected="selected"'; ?>>3-c</option>
</select>
<input type="submit"/><br />
</form>
</body>
</html>
<?php
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I would not use heredoc syntax ("<<<") to print HTML.
Try this out, i made one submit button, and re selected the values after submit :
<?php
// formtest_2.php
$name_vid = $name_type = $name_model = "";
if (isset($_POST['vid']))
$name_vid = ($_POST['vid']);
else
$name_vid = "no";
if (isset($_POST['type']))
$name_type = sanitizeString($_POST['type']);
else
$name_type = "no";
if (isset($_POST['model']))
$name_model = sanitizeString($_POST['model']);
else
$name_model = "no";
///////////////////
if($name_vid == 'apple')
{
$v1 = 'selected';
}
elseif($name_vid == 'cherry')
{
$v2 = 'selected';
}
elseif($name_vid == 'orange')
{
$v3='selected';
}
////////////////////////
if($name_type == 'green')
{
$t1 = 'selected';
}
elseif($name_type == 'red')
{
$t2 = 'selected';
}
elseif($name_type == 'orange')
{
$t3='selected';
}
///////////////////////
if($name_model == '1-a')
{
$m1 = 'selected';
}
elseif($name_model == '2-b')
{
$m2 = 'selected';
}
elseif($name_model == '3-c')
{
$m3='selected';
}
?>
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form name="fruite_form" action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="" selected>Product</option>
<option <?=$v1?> value = "apple">apple</option>
<option <?=$v2?> value = "cherry">cherry</option>
<option <?=$v3?> value = "orange">orange</option>
</select>
<select name="type" size="1">
<option value="" selected>Color</option>
<option <?=$t1?> value = "green">green</option>
<option <?=$t2?>value = "red">red</option>
<option <?=$t3?>value = "orange">orange</option>
</select>
<select name="model" size="1">
<option value="" selected>Model</option>
<option <?=$m1?> value = "1-a">1-a</option>
<option <?=$m2?>value = "2-b">2-b</option>
<option <?=$m3?>value = "3-c">3-c</option>
</select>
<input name="submitButtom" id="submitButton" type="submit"/><br />
</form>
</body>
</html>
<?
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
Feel free top add back your submit buttons.
But give each a unique name and also don't forget to name your form, and as a good practice, give then an id too which will be the same as name attribute.
Update: Just to make sure you are really getting a post, since this is your initial question, print this at the end of your code
echo $_POST['vid'] . ' ' . $_POST['type'] . ' ' . $_POST['model'] . '<br/><br/>';
and see if post really holds the value after submission, if you get a value from post, but not from your assigned variables, then check your conditions used at the top to assign your values.
// you need to check if post isset and has an actual value, only than, the varibale should be assigned. Just like what Sithu said.