Calculate total price of two books using PHP and HTML - php

I want to know what can be the way using php and html such that I am provided a dropdown of books, I need to select exactly two choices out of that drop down and then calculate sum of price of both the books.
Assuming I had hardcoded the Books say:
Book 1 - $5
Book 2 - $15
Book 3 - $50
I know with if it was to select only one book. But no idea for this one. Please help
Code :
<?php
if(isset($_POST['formSubmit']))
{
$varCurrentBook = $_POST['formBook'];
$errorMessage = "";
if(empty($varCurrentBook))
{
$errorMessage = "<li>You forgot to select a Book!</li>";
}
if($errorMessage != "")
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
else
{
switch($varCurrentBook)
{
//Can use here to find what option is clicked
}
exit();
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for='formBook'>Select a Book</label><br>
<select name="formBook">
<option value="0">Select a Book...</option>
<option value="15">The Secret</option>
<option value="10">The Fairy Tales</option>
<option value="5">All about words</option>
<option value="100">Pinaacle Studio</option>
<option value="120">Harry Potter</option>
<option value="200">Thinking in Java</option>
</select>
<input type="submit" name="formSubmit" value="Submit" />
</form>

You need to use a multiple select as:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for='formBook'>Select a Book</label><br>
<select name="formBook[]" multiple><!--The multiple attribute-->
<option value="0">Select a Book...</option>
<option value="15">The Secret</option>
<option value="10">The Fairy Tales</option>
<option value="5">All about words</option>
<option value="100">Pinaacle Studio</option>
<option value="120">Harry Potter</option>
<option value="200">Thinking in Java</option>
</select>
<input type="submit" name="formSubmit" value="Submit" />
</form>
Also note how I changed name from formBook to formBook[]. This changes $_POST['formBook'] to an array of options.
Then you can access it as:
<?php
foreach ($_POST['formBook'] as $names)
{
print "You have selected $names<br/>";
/*Your also need to change your code here accordingly.*/
}
?>

You have to use multiple select with jquery
see: HTML Multiselect Limit
<select name="formBook">
have to become:
<select name="formBook[]" multiple">
Then you can sum all selected elements
if(isset($_POST['formSubmit']))
{
$sum = array_sum($_POST['formBook']); // Sum of all selected elements
...
}

As ARBY answered correct you have to add the multiple attribute to your select element:
<select name="formBook" multiple>
This sends the value attribute. (E.g. 0 / 15 / 10)
So you can check if you have exactly two books like this:
//Check if the user has selected exactly two books
$formBooks = $_POST['formBook'];
if(count($formBooks) !== 2){
//TODO: return error message that user has to select two books
}
//Calculate the value
$result = array_sum($formBooks);
//TODO: return value

Related

Having trouble validating the <select> element within a larger <form> element - it won’t return an error message

I’ve been building a series of webpages that allows for dynamic data manipulation (CRUD). The pages are built with HTML, CSS, and PHP.
At this stage of the project, my goal is to have the site return an error message if data is not entered into a particular field.
I've made a small sandbox for the problem.
At the top of the page, I included the following PHP logic to outline the variables and how the page will behave if data is entered into the form fields (or not entered):
$routeType = "";
$hasRouteType = false;
$routeTypeError = false;
if( isset($_POST["add"]) ) {
if( isset($_POST['route-type']) ) {
$routeType = $_POST['route-type'];
if($routeType) {
$hasRouteType = true;
} else {
$routeTypeError = "Please select a route type.";
}
}
}
I made a dropdown menu as one of the elements in the form as follows:
<form method='POST'>
<field>
<label>Route Type</label>
<select name="route-type" id="route-type">
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
<option value="interstate">Interstate</option>
<option value="stateRoute">State Route</option>
<?php if($routeTypeError) { ?>
<p class='error'><?=$routeTypeError?></p>
<?php } ?>
</select>
</field>
<form>
<button class='route-button' type="submit" name='add'>Add route</button>
At this stage, when the user doesn't choose anything from the dropdown, no error message is returned -- again, this is the goal of this stage of the project.
Steps I've tried to solve the problem so far (these didn't work)
I’ve tried changing the logic in the principal foreach statement.
if($routeType) {
$hasRouteType = true;
if($routeType != "") {
$hasRouteType = true;
I’ve tried changing the data type of the $routeType variable when it's initialized.
I’ve tried adding selected=“true” and disabled=“disabled” to the top element in the dropdown menu to make it the first thing that appears on the page — and also to make it impossible for the user to select it as an option from the menu.
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
I've been told that "looping through the option elements" might be a possible solution, but I don't know how to implement this.
My goal is to have the error message "Please select a route type." returned if the user does not select anything from the dropdown menu.
Thanks very much for the help!
You need an option field with empty value and the required.
Solution with client-side check
<select name="route-type" id="route-type" required="required">
<option value="">What type of route is this?</option>
<option value="A" >Select A</option>
<option value="B" >Select B</option>
</select>
You don't need php for this.
Try to submit this without select a value and you will get an error message.
All html and javascript checks are just goodies, you always have to check all values ​​with php(when you use php) when you get them from a form.
Never trust any data and check every data you receive!
UPDATE:
Maybe this is a possible solution you looking for with php:
Solution with php check
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
If you wan't to check with the required option also on the client-side use:
<select name="route_type" required="required">
You can also build your option fields with a loop and use the values from the array.
Solution with php check and custom error message(javascript alert):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
echo "<script>alert('Please select type')</script>";
}
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
Solution with php check and custom error message(php in option field):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
$MESSAGE = 'NO TYPE SELECTED';
}
else{
$MESSAGE = 'SELECT A TYPE';
}
?>
<form method="post">
<select name="route_type">
<option value=""><?php echo $MESSAGE; ?></option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
This is just a small example of how it could work, of course you can further optimize and adapt the code

MYSQL SELECT with user selected OPTION values

I am trying to filter out a MYSQL table according to user selected values in my php file list.php
My table users have field stdYr, in which elements have values of S00, S01, ... S40.
in html body, I have this chunk of code:
<form method="post" role="form" action="list.php">
<div>
<select multiple>
<option value="all">Select</option>
<option value="S00">74</option>
<option value="S01">75</option>
<option value="S02">76</option>
...
<option value="S40">114/option>
</select>
<button type="submit"></button>
</div>
</form>
And then, I want to select those with selected stdYr values.
The approach I could come up with is passing the values of option through $_POST:
if(isset($_POST['S00']) || isset($_POST['S11']) || ...
... || isset($_POST['S40'])) {
/*some code to get only those set values*/
$query="SELECT * FROM users WHERE stdYR = '/*some stuff*/'";
}
But with different possible selections of values, I couldn't figure out how exactly to do this...
And even with the solution, I see this approach very repetitive and silly.
How am I supposed to deal with such things?
I greatly appreciate your help! Thanks :D
Your form is incorrect. Your select MUST have a name attribute for it to get submitted to the server.
<select name="options[]" multiple>
^^^^^^^^^^^^^^^
<option ...>
...
</select>
Note the [] on the name field. That'll tell PHP to accept multiple values, making $_POST['options'] an array itself. Then it's a simple matter of:
foreach($_POST['options'] as $option) {
insert_into_db($option);
}
Use this way:
<form method="post" role="form" action="list.php">
<div>
<select name="MyOptions[]" multiple>
<option value="all">Select</option>
<option value="S00">74</option>
<option value="S01">75</option>
<option value="S02">76</option>
...
<option value="S40">114/option>
</select>
<button type="submit"></button>
</div>
</form>
print '<pre>';
print_r($_POST);
$selectOption = $_POST['MyOptions']; //get post result and then work as you wish
You could try this :
<select name="stdYR[]" multiple>
<?php
$stdYR = $_POST['stdYR'];
$stdYR_ct = count($stdYR);
$i=0;
while($i < $stdYR_ct){
$stdYR_SQL .= "'$stdYR[$i]',";
$i++;
}
if (preg_grep("/All/i", $stdYR) or ($stdYR_ct < 1)){
$stdYR_SQL = "";
}else{
$stdYR_SQL = eregi_replace(",$",'',$stdYR_SQL);
$stdYR_SQL = " AND stdYR IN($stdYR_SQL)";
}
$query = "SELECT * FROM users WHERE 1=1 $stdYR_SQL ";
?>

How to select the dropdownlist value and validate it

I have created the dropdown list in my index page i want to select the one value from that list and validate it if not selected any value the code for that is as follows:
<form action="" method="post">
<select value="state" name="state">
<option selected="">---please enter---</option>
<option value="1">andhra</option>
<option value="2">thamil</option>
<option value="3">kerela</option>
</select>
</form>
php code for the above file is as follows:
<?php
if(!empty($_POST['state'])) {
$state = $_POST['state'];
}
else {
echo "required";
}
?>
I dont want to be select the first option in selection list please enter to be selected but the code which I have used is taking that value also I want relevant code how to validate that list?
I prefer adding a disabled attribute to the placeholder option, that way, a user has to choose something if they click the drop-down:
<select value="state" name="state">
<option selected disabled>---please enter---</option>
<option value="1">andhra</option>
<option value="2">thamil</option>
<option value="3">kerela</option>
</select>
Quick demo: http://jsfiddle.net/hxxJZ/
something like this should to the trick:
<form action="" method="post">
<select name="state">
<option value="0" selected>---please enter---</option>
<option value="1">andhra</option>
<option value="2">thamil</option>
<option value="3">kerela</option>
</select>
</form>
php
<?php
if( 0 != $_POST['state'] ) {
$state = $_POST['state'];
}
else {
echo "required";
}
?>
your HTML is not right,
try edit this line
<option selected=""...
to this one
<option selected value="">---
select elements do not have an (HTML) value attribute, so remove value="state".
The selected attribute should be selected="selected" (or just SELECTED).

Multiple submissions from one page

am trying to allow a user to delete a certain image with is in a certain directory. I need them to first specify a directory and then the image which they want to delete.
I have been able to accomplish what I thought would be the hard part, of having their Gallery selection result in a drop-down populated only with the name of those images in their selected gallery.
My issue is that I cannot seem to get the submit button for my second form to trigger the if statement that will delete the files and remove the row from the table. I thought someone here might peruse my code and tell me what I am missing :(
thanks a ton!
<form action ='' name="form1" method='POST' enctype="multipart/form-data">
<p>Select Gallery: <select name="gal" style="color:black;">
<option value="" style="color:black;"><?php echo $gal; ?></option>
<option value="graphicdesign/logos" style="color:black;">GD logos</option>
<option value="graphicdesign/webdesign" style="color:black;">GD website design</option>
<option value="graphicdesign/advertisements" style="color:black;">GD Advertisements</option>
<option value="fineart/nature" style="color:black;">FA Nature</option>
<option value="fineart/people" style="color:black;">FA People</option>
<option value="fineart/landscapes" style="color:black;">FA Landscapes</option>
<option value="photography/misc" style="color:black;">PG Misc</option>
<option value="photography/nature" style="color:black;">PG Nature</option>
<option value="photography/people" style="color:black;">PG People</option>
</select></p>
<input type="submit" value="Set Galery" style="color:black;"></p>
<?php
$connect = mysql_select_db("cynthie") or die("couln't find db on 2 :(");
$metaData = mysql_query("SELECT `name`, `path_full`, `path_thumb`, `galId` FROM `images`") or die("couln't find table :(");
$gal = $_POST['gal'];
if (isset($_POST['gal']))
{
echo '<form action ="" method="POST" enctype="multipart/form-data"><p>Select Image: <select name="toDelete" style="color:black;"><p><option style="color:black;">select img</option></p>';
while ($displayData = mysql_fetch_assoc($metaData))
{
$names = $displayData['name'];
$path_full = $displayData['path_full'];
$path_thumb = $displayData['path_thumb'];
$galDb = $displayData['galId'];
if ($galDb != $gal)
{}
else
{
echo '<p><option style="color:black;">'.$names.'</option></p>';
}
}
echo '</select><p><input type="submit" value="Delete" style="color:black;"></p></form>';
$connect = mysql_select_db("cynthie") or die("couln't find db on 4 :(");
$delete = mysql_query("SELECT `id` FROM images WHERE name='$toDelete'") or die("couln't find table on line 81 :(");
$toDelete = $_POST['toDelete'];
if (isset($_POST['toDelete']))
{
unlink($path_full);
unlink($path_thumb);
mysql_query("DELETE FROM images WHERE `id`=$delete");
unset($delete);
echo '<p>removed!</p>';
}
else
{}
}
?>
You have your toDelete check inside the gal check, so you need to have $_POST['gal'] and $_POST['toDelete'] being sent. I don't see gal in your second form, so just add <input type="hidden" name="gal" value="{$_POST['gal']}" />.

How to Keep the selected value of the select box after Form POST or GET

Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>

Categories