I'm trying to show an error message if a checkbox has not been selected. I've managed to get it done input field, but unsure of how to get it done with a checkbox. This is what I have so far:
<?php
# check if data has been posted
if (!empty($_POST)) {
# keep track validation errors
$author_error = null;
$categories_error = null;
# keep track of post values
$author = $_POST['author'];
$categories = $_POST['categories'];
# validate input
if (empty($author)) {
$author_error = 'Please select author';
$valid = false;
}
if (empty($categories)) {
$categories = 'Please select categories';
$valid = false;
}
# if data is valid, insert into the database
if ($valid) {
}
}
?>
<div class="control-group <?php if (!empty($author_error)){ echo 'error'; } ?>">
<label class="control-label">Author</label>
<div class="controls">
<select name="author" id="author">
<option value="">Select one</option>
<?php $sql2 = 'SELECT id, name FROM author';
foreach ($dbConnection->query($sql2) as $data2) { ?>
<option value="<?php echo $data2['id']; ?>"
<?php if(isset($author) && $author == $data2['id']) { echo 'selected'; } ?>>
<?php echo $data2['name']; ?>
</option>
<?php } ?>
</select>
<?php if (!empty($author_error)) { echo '<span class="help-inline">' . $author_error . '</span>'; } ?>
</div>
</div>
<div class="control-group <?php if (!empty($categories_error)){ echo 'error'; } ?>">
<fieldset>
<legend class="control-label">Categories:</legend>
<?php $sql3 = 'SELECT id, name FROM category';
foreach ($dbConnection->query($sql3) as $data3) { ?>
<div class="controls">
<label for="category<?php echo($data3['id']);?>">
<input type="checkbox" name="categories" id="categories" value="<?php echo($data3['id']); ?>"
<?php if(isset($_POST['categories']) && in_array($data3['id'], $_POST['categories'])) { echo 'checked'; } ?>>
<?php echo($data3['name']); ?>
</label>
</div>
<?php } ?>
</fieldset>
<?php if (!empty($categories_error)) { echo '<span class="help-inline controls">' . $categories_error . '</span>'; } ?>
</div>
Where am I going wrong with the categories field?
Check it like:
isset($_POST['categories'])
On line #62 you are checking if $categories_error is empty but you are using variable $categories for storing error message on line #19
Related
I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>
Forms input value variables are the same changing only labels for it from DB. When form selected other ones is hidden with "style.display = "none".
The problem that I face how to prevent sending empty values from none visible input fields?
Tried a trim function but didn't work for me. Maybe didn't use it correctly.
I'm trying to accomplish that input value would stay the same regardless of what user would select and only labels would change.
dump output
<?php
if (isset($_POST["save"])) {
if (empty($_POST['price'])) {
$error["price"] = "Price Required";
} else {
$price = $_POST["price"];
}
if (array_filter($error)) {
echo "Input error";
} else {
$price = ($_POST['price']);
$value1 = ($_POST['value1']) ?? null;
$value2 = $_POST['value2'] ?? null;
$value3 = $_POST['value3'] ?? null;
}
}
// insert size
$sql = "INSERT INTO valueSize(value1, value2, value3) values('$value1', '$value2, '$value3')";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<!DOCTYPE html>
<html lang="en">
<form action="">
<?php foreach ($categoriesTypeId as $key): ?>
<div class="dropItem invisible" id="<?php echo $key['id'] ?>">
<label for="value1"><?php echo $key['value1Type'] ?>:</label>
<input type="text" name="value1[]" value="<?php echo $value1 ?>">
<div class="error"><?php echo $error['value1'] ?></div>
<?php if (isset($key['value2Type'])) {?>
<div class="inputCheck">
<label for="value2"><?php echo $key['value2Type'] ?>
:</label>
<input type="text" name="value2" value="<?php echo $value2 ?>">
<div class="error"><?php echo $error['value2'] ?></div>
</div>
<?php
}
;
?>
<?php if (isset($key['value3Type'])) {?>
<div class="inputCheck">
<label for="value3"><?php echo $key['value3Type'] ?>
:</label>
<input type="text" name="value3" value="<?php echo $value3 ?>">
<div class="error"><?php echo $error['value3'] ?></div>
</div>
<?php
} else {
}
?>
<?php endforeach;?>
</form>
</html>
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.
This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.
I currently have a drop down box than when one of the options is selected it will echo-
"Your Favourite Car Is (option)
What I need to do now is change this so its a text box but the user can only type in one of the options within the array and if another one was chosen it would say you cannot have this as one of the choices and it would also be able to type in more than one so theoretically it could echo-
"Your Favourite Car is Mazda, Nissan, Renault!"
Here is the code i have now for the drop box that i have working.
<form method="post">
<div id="dropdown">
<?php
if(isset($_POST['cars']))
{
$mycar=$_POST['cars'];
}
else
{
$mycar="";
}
$array1 = array('Volkswagen' , 'Renault' , 'Land Rover');
echo' <select name="cars" onchange="this.form.submit()">';
foreach($array1 as $cars)
{ ?>
<option value="<?php echo $cars; ?>" <?php if($mycar==$cars) echo "
"selected='selected'"; ?> ><?php echo $cars; ?></option>
<?php
}
echo'</select>
</div></form>';
?>
<div id="result">
<?php
echo "Your favourite car is $mycar";
?>
</div>
EDIT: I have attempted this and what i currently have always echo's "this car isnt among the selection" and nothing else and nothing i enter into the text box seems to effect this
here is the code i have
<?php
$cars = array("Volkswagen","Renault","Land Rover");
?>
<form action="array.php" method="post">
<center> <input type="text" name="cars" id="cars" />
<input type="submit" /> </center>
<?php
if (in_array($_POST, $cars)) {
echo "Your Favourite Car is $_POST";
}
else {
echo "This car is not among the selection";
}
?>
</form>
You can easily control the user input by checking it before:
<form method="post">
<div id="dropdown">
<?php
// Car types
$carTypes = array('Volkswagen' , 'Renault' , 'Land Rover');
$wrongCarChoosen = false ;
if(isset($_POST['cars'])) {
$mycar = $_POST['cars'];
if (!in_array($mycar, $carTypes)) {
$wrongCarChoosen = true ;
}
}
else {
$mycar = "";
}
echo' <select name="cars" onchange="this.form.submit()">';
foreach($carTypes as $carName){ ?>
<option value="<?php echo $cars; ?>"
<?php
if($mycar == $carName) echo "
"selected='selected'"; ?> >
<?php echo $carName;
?></option>
<?php
}
echo'</select>
</div></form>';
?>
<div id="result">
<?php
if ($wrongCarChoosen) {
echo "Your choice ".$mycar." is not contained in ".implode($carTypes, ',') ;
}
else {
echo "Your favourite car is $mycar";
}
?>
</div>
You must edit the form to accept multiple values. And you can check the user values before you echo the text.
<form method="post">
<div id="dropdown">
<?php
$array1 = array('Volkswagen' , 'Renault' , 'Land Rover');
$error = false;
if(isset($_POST['cars']))
{
$mycar=$_POST['cars'];
foreach ($mycar as $car)
{
if (!in_array($car, $array1))
{
$error = $car;
}
}
}
else
{
$mycar=Array();
}
echo' <select name="cars[]" multiple="multiple">';
foreach($array1 as $cars){ ?>
<option value="<?php echo $cars; ?>" <?php if(in_array($cars, $mycar)) echo "\"selected='selected'"; ?> ><?php echo $cars; ?></option>
<?php
}
echo'</select>
<input type="submit" name="submit" value="submit" />
</div></form>';
?>
<div id="result">
<?php
if ($error===false) echo "Your favourite car is ".implode(', ', $mycar);
else echo $error . ' is not contained by ' . implode(', ', $array1);
?>
</div>