List Box Should be Drop down - php

to every one
I have some values in my data base i Want to display them with check boxes.
those values should be display when i click at the button. This should not in combo box.
because I want to post multiple values at one time.
Please help with thanks
<?php
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs=0;
while($girlslist=mysql_fetch_array($womenlist))
{
$gs++;
?>
<li style="background-color:#CCC; width:150px;"><label for="chk1"><input type="checkbox" name="chk_<?php echo $gs?>" id="chk<?php echo $gs?>" value="<?php echo $girlslist['calName'];?>" <?php if($_REQUEST['chk_'.$gs]==$girlslist['calName']){?> checked="checked"<?php }?>><?php echo $girlslist['calName']." ".$girlslist['calDesc']; ?> </label></li>
<?php }?>

You could limit the number of columns in your query (not SELECT * ...). You've put the <input> inside the <label>. The <label>'s for="" attribute is hardcoded as chk1. You could take out the inline style="" on the <li> and put it into a stylesheet. I've "tidied" it up a bit (untested):
$womenlist = mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs = 0;
while( $girlslist = mysql_fetch_array($womenlist) )
{
$gs++;
echo '<li style="background-color:#CCC; width:150px;">'
. '<label for="chk' . $gs . '">' . $girlslist['calName'] . ' ' . $girlslist['calDesc'] . '</label>'
. '<input type="checkbox" name="chk_' . $gs . '" id="chk' . $gs . '" value="' . $girlslist['calName'] . '"
. (($_REQUEST['chk_'.$gs]==$girlslist['calName']) ? 'checked="checked"' : '') . '></li>';
}

Not sure entirely what you're asking for here (as it looks like you already have this working with checkboxes), but you can in fact post multiple values with a select box. You just use the multiple attribute, and specify the name as an array with the square brackets:
<form action="yourscript.php" method="post">
<select name="women[]" multiple="multiple">
<option value="woman1_name">Woman 1</option>
<option value="woman2_name">Woman 2</option>
<option value="woman3_name">Woman 3</option>
</select>
<input type="submit" />
</form>
If you post a form with this, selecting woman 2 & 3, var_dump($_POST); yields:
array(1) {
["women"]=>
array(2) {
[0]=>
string(11) "woman2_name"
[1]=>
string(11) "woman3_name"
}
}
Alternatively, if you want the values of your checkboxes to come through in a similar fashion, change them so they all have the same name, but with the square brackets on the end. This HTML would yield similar POST data:
<input type="checkbox" name="women[]" value="Woman 1" />
<input type="checkbox" name="women[]" value="Woman 2" />
<input type="checkbox" name="women[]" value="Woman 3" />
So, to create a dropdown using this, here's an adaptation of your code. I believe this is what you're after:
<?php
$options = '';
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
while($woman=mysql_fetch_array($womenlist)) {
$options .= '<option value="'.$woman['calName'].'"'.((!empty($_REQUEST) && in_array($woman['calName'],$_REQUEST['women'])) ? ' selected="selected"' : '').'>'.$woman['calName'].' '.$woman['calDesc'].'</option>';
}
?>
<label for="women">Women:</label>
<select id="women" name="women[]" multiple="multiple">
<?php echo $options; ?>
</select>

Related

How can I change the selected option in select atribute using the php value that i have?

I want my select atribute to change it's selected option depending on php $choice. For example if I chose FOOD ASC (it's option 1) i want to make it selected after i press the button with name "sortbutton"
if(isset($_POST['sortbutton']))// if button pressed
{
$choice = $_POST['sort_select'];
if($choice == 0){...there was some code //if selected option == 0
$qr_result = mysqli_query($db, "Select *
from `menu`
WHERE id>0
ORDER BY price ASC")
or die(mysqli_error());
echo '<table class="tam" style = "position:fixed; top: 110px;">'; //table
echo '<td>' . 'Блюдо' . '</td>';
echo '<td>' . 'Состав' . '</td>';
echo '<td>' . 'Цена' . '</td>';
while($data = mysqli_fetch_array($qr_result)){
echo '<tr>';
echo '<td>' . $data['product'] . '</td>';
echo '<td>' . $data['consistency'] . '</td>';
echo '<td>' . $data['price'] . '</td>';
echo '</tr>'; //outputing database
HTML
<form action="" method="POST">
<div class="sorti">
<select name="sort_select" >
<option value="0" name = "value1">PRICE ASC</option>
<option value="1" name = "value2">PRICE DESC</option>
<option value="2" name = "value3">NAME ASC</option>
<option value="3" name = "value4">NAME DESC </option>
</select>
<button name = "sortbutton">Show menu</button>
</form>
<form action="" method="POST">
<div class="sorti">
<select name="sort_select" >
<option value="0" name = "value1" <?php echo $choice== 0?"selected":""; ?>>PRICE ASC</option>
<option value="1" name = "value2" <?php echo $choice== 1?"selected":""; ?> >PRICE DESC</option>
<option value="2" name = "value3" <?php echo $choice== 2?"selected":""; ?> >NAME ASC</option>
<option value="3" name = "value4" <?php echo $choice== 3?"selected":""; ?> >NAME DESC </option>
</select>
<button name = "sortbutton">Show menu</button>
</div>
</form>
I assume , the next page renders the same form again doing above on the html should work.
I would probably want to write this better but setting selected on the option is a solution you should go for
The option element does not have a name attribute, that should be removed, the name of the dropdown selection is of course the name used in the <select name="sort_select"> element then a simple ternary test, testing the value of $choice
will set the selected attribute for you like this
<form action="" method="POST">
<select name="sort_select">
<option value="0" <?php echo $choice==0 ? 'selected="selected"' : '';?>>PRICE ASC</option>
<option value="1" <?php echo $choice==1 ? 'selected="selected"' : '';?>>PRICE DESC</option>
<option value="2" <?php echo $choice==2 ? 'selected="selected"' : '';?>>NAME ASC</option>
<option value="3" <?php echo $choice==2 ? 'selected="selected"' : '';?>>NAME DESC </option>
</select>
<button name="sortbutton">Show menu</button>
</form>

Pre-populating and compare select field with 'selected' option

I am pulling form data from home.php into results.php and using $_GET['xxxxx'] to pre-populate fields of another form. I can populate input fields okay, but how would you compare an option field and $sale_type to selected if equal?
home.php
<form action="results.php" method="GET">
<input id="address" name="address" type="text" class="form-control1"/>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<input name="submit" type="SUBMIT" value="Next" class="form-control1">
</form>
results.php
Option fields are already populated to ensure the form will work if it's used without results from home.php. I need to compare $sale_type value with the option of name="sale_type and if equal change that option value to selected.
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?>
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
What I'd like results to do
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?> //If value is Sale
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale" selected>For Sale</option> //Change to selected if equal
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
You could check and then marked as selected when condition satisfy. One of the example is :
<option value="Sale" <?php if(condition) echo "selected" ?> >For Sale</option>
You'd compare the variable to value in the option tag like so:
<option value="Sale" <?= ($sale_type === 'Sale') ? 'selected' : ''; ?>>For Sale</option>
Another, option, if you will, is to set an array of sale_types. Instead of checking each individual option value, you could loop through the options and check there. Like this:
$sale_types = [
'Sale' => 'For Sale',
'Rent' => 'To Rent',
'SomeOtherType' => 'Something Else'
];
Then in select element:
<? foreach ($sale_types as $sale_value => $sale_option): ?>
<option value="<?= $sale_option; ?>" <?= ($sale_type === $sale_option) ? 'selected' : ''; ?>><?= $sale_value; ?></option>
<? endforeach; ?>
If you're going to do very much of this at all, my recommendation is to build a PHP function. Otherwise, you end up with a bunch of mixed HTML / PHP to check conditions.
This allows you to set up and display a dropdown quickly any time you need to.
Something like this would do what you want and would be re-usable:
// Function to generate the HTML for a select
function dropdown_array( $name, $value, $array, $placeholder = '' ) {
$temp_input = '<select name="' . $name . '"';
$temp_input .= ( $placeholder ) ? ' placeholder="' . $placeholder . '"' : '';
$temp_input .= '>' . PHP_EOL;
if ( is_array( $array ) ) {
foreach ( $array as $val => $text ) {
$temp_input .= '<option value="' . $val . '"';
if ( $value === $val ) {
$temp_input .= ' selected';
}
$temp_input .= '>' . $text . '</option>' . PHP_EOL;
}
}
$temp_input .= '</select>' . PHP_EOL;
return $temp_input;
}
Then, in your situation, usage would look like so:
$array = array( 'Sale' => 'For Sale', 'Rent' => 'To Rent' );
echo dropdown_array( 'sale_type', $sale_type, $array, 'Sale Type' );

Drop down list in php only working as a default checkbox

I am trying to convert my search page from using a checkbox styled method to being able to use a drop down box to select each separate title header as a potential search option. However when converting this the title drop down box still acts as its old checkbox style, being that it only shows the data that is stored within the title name no matter which title is selected.
PHP Section:
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
// Set up our error check and result check array
$error = array();
$results = array();
// First check if a form was submitted.
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
$searchTerms = trim($_GET['search']);
$searchTerms = strip_tags($searchTerms); // remove any html/javascript.
if (strlen($searchTerms) < 3) {
$error[] = "Search terms must be longer than 3 characters.";
}else {
$searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
}
// If there are no errors, lets get the search going.
if (count($error) < 1) {
$searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE ";
// grab the search types.
$types = array();
$types[] = isset($_GET['body'])?"`sbody` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['desc'])?"`sdescription` LIKE '%{$searchTermDB}%'":'';
$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
if (count($types) < 1)
$types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked
$andOr = isset($_GET['matchall'])?'AND':'OR';
$searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title.
$searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
if (mysql_num_rows($searchResult) < 1) {
$error[] = "The search term provided {$searchTerms} yielded no results.";
}else {
$results = array(); // the result array
$i = 1;
while ($row = mysql_fetch_assoc($searchResult)) {
$results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />";
$i++;
}
}
}
}
function removeEmpty($var) {
return (!empty($var));
HTML Section:
<body>
<?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">
Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
Search In:<br />
Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> |
Title: <form action="form_action.asp">
<select name="title">
<option value="Test Simple Search 1">Test Simple Search</option>
<option value="Searching Made Easy 101">Search Made Easy</option>
<option value="Gateway to Information">Gateway to Information</option>
<option value="The Gaming World as we Know it">Gaming World</option>
<option value="Hundreds of Ants Attacking">Ants Attacking</option>
<?php echo isset($_GET['title'])?"checked":''; ?> </select> |
Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
<input type="submit" name="submit" value="Search!" />
</form>
<?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>
The option values that are used are the name as the titles stored within stitle within the mysql database. Have I simply implemented them wrong or is my php used after title completely incorrect?
Any advice on what I can do or any code snippets from yourselves would be very appreciated.
Ok I think I get your issue.
First if you want to select more than one item in a dropdown, then you need to add the multiple attribute to the select tag like this <select name="title" multiple>
Now when the user holds the CTRL key down and clicks entries, each clicked entry gets selected.
Secondly the data identifying the selected items will now be returned as an array in $_GET['title'] so if the first 2 options are selected the $_GET['title'] array would look something like this :-
0 - "Test Simple Search 1"
1 - "Searching Made Easy 101"
Now in order to re-select the items that were selected by the user when they submitted the form you have to set the selected="selected" attribute on each of the <option> tags that equate to the selected rows of the dropdown so they look selected when the user sees the form again.
<?php
function was_i_selected($selected_options, $value) {
if ( in_array($value, $selected_options, true) ) {
return 'selected="selected"';
} else {
return NULL;
}
}
?>
<select name="title" multiple>
<option <?php echo was_i_selected($_GET['title'], 'Test Simple Search 1');?> value="Test Simple Search 1">Test Simple Search</option>
<option <?php echo was_i_selected($_GET['title'], 'Searching Made Easy 101');?> value="Searching Made Easy 101">Search Made Easy</option>
<option <?php echo was_i_selected($_GET['title'], 'Gateway to Information');?> value="Gateway to Information">Gateway to Information</option>
<option <?php echo was_i_selected($_GET['title'], 'The Gaming World as we Know it');?> value="The Gaming World as we Know it">Gaming World</option>
<option <?php echo was_i_selected($_GET['title'], 'Hundreds of Ants Attacking');?> value="Hundreds of Ants Attacking">Ants Attacking</option>
</select>
Now that look very clumsy and we have not checked that $_GET['title'] actually exists, so I would probably do it like this :-
<?php
$options = array(
'Test Simple Search 1' => 'Test Simple Search',
'Searching Made Easy 101' => 'Search Made Easy',
'The Gaming World as we Know it' => 'Gaming World',
'Hundreds of Ants Attacking' => 'Ants Attacking'
);
<select name="title" multiple>
<?php
foreach ( $options as $val => $label ) {
if ( ! empty($_GET['title'] ) {
$sel = in_array($val, $_GET['title'], true) ? 'selected="selected"' : '';
echo '<option ' . $sel . ' value="' . $val . '">' . $label . '</option>';
} else {
echo '<option value="' . $val . '">' . $label . '</option>';
}
}
?>
</select>

Retain dynamically selected value from drop down list, but still be able to see list after submit

I have got the following form:
<div id="Quick_find_container">
<form action="" method="post" target="_self">
<div id="qcategory_1">Product</div>
<div id="qcategory">
<select name="Category" class="dropmenu" id="Category"onchange="this.form.submit()">
<option value="">Any</option>
<option value="Keyboard"<?php if ($_POST['Category']=="Keyboard") {echo "selected='selected'"; } ?>>Keyboard</option>
<option value="Piano"<?php if ($_POST['Category']=="Piano") {echo "selected='selected'"; } ?>>Piano</option>
</select>
</div>
<div id="qbrand_1">Brand</div>
<div id="qbrand"><select name='Manufacturer' onchange="this.form.submit()">
<?php
echo '<option value="">Any</option>';
$value = $_POST['Manufacturer'];
while ($row = mysql_fetch_array($RS_Search)) {
echo "<option value=" . $row['Manufacturer'] . " ' . (selected == $value ? ' selected' : '') . '>" . $row['Manufacturer'] . "</option>";
}
?>
</select>
</div>
<div id="qsubmit">
<input name="Search2" type="submit" id="Search2" value="Submit">
</div>
</form>
</div>
<?php echo $_POST['Category']; ?>
<?php echo $_POST['Manufacturer']; ?>
Echo post Category and Manufacturer are purely to see what it is submitting.
My problem is the second drop down menu. I would like to display after something is selected what the selected value was. At the moment it just jumps back to the default value Any even though the out put of POST_[Manufacturer'] is correct.
Is there a way to display the selected value like in the first drop down menu? I still would like to keep the values to choose from the database as well. But just display the selected value.
Any help welcome
Your line that echos the option has a lot of problems with quotes. This will fix it:
while ($row = mysql_fetch_array($RS_Search)) {
$selected = $_POST['Manufacturer'] == $row['Manufacturer'] ? 'selected' : '';
echo '<option ' . $selected . ' value="' . htmlspecialchars($row['Manufacturer']) . '">' . htmlspecialchars($row['Manufacturer']) . '</option>';
}
Side note: remember to use htmlspecialchars() or similar when outputting variables into HTML to prevent XSS.
In theory the code you have there might work altough i'd had made it like this
while ($row = mysql_fetch_array($RS_Search)) {
$selected = ($_POST['Manufacturer'] == $row['Manufacturer']) ? 'selected="selected":'';
echo '<option '.$selected.'>' . $row['Manufacturer'] . '</option>";
}?>
You do not need value if you have the same thing within the tag. Also you were missing some quote marks in your tag. Learn to simplify your code so it's easier to understand.

Adding selected to option drop down list based on user's previous selection

In the vendor drop down menu I need to dynamically add "selected" based on what the user input at the previous screen. I have what I think the loop will basically look like but I can't get it to work. Any help would be much appreciated, I have looked at other examples but they are not like this one. Here is my code:
<?php
$set_date =$_POST['set_date'];
include "../include/setup.inc.php";
$query="select * from quote_distro where set_date ='2011-10-05'";
$result = mysql_query($query);
if (!$result) {echo "<p><b>".$query ."</b></p>";echo 'MySQL Error: ' . mysql_error(); return;}
echo '<br /><br />';
echo '<form name="edit_quote_setting_'.$row['qdid'].'" action="'.$self.'" method="post"><table align="center" border="1" width="800px">
<tr><td width="10%">Email:</td><td width="20%"><input type="text" MAXLENGTH=40 size="30" name="email" value="'.$row['agent_email'].'"></td>
<td width="10%">#Quote:</td><td width="10%"><input type="text" MAXLENGTH=4 size="3" name="num_quote" value="'.$row['num_quote'].'"></td>
</td><td width="10%">Vendor</td><td width="40%"><select id="vendor1" name="vendor[1]">
<option value="Regent Seven Seas Cruises"'.test().'>Regent</option>
<option value="Silversea Cruises">Silversea</option>
<option value="Oceania Cruises">Oceania</option>
<option value="Windstar Cruises">Windstar</option>
<option value="Paul Gauguin Cruises">Paul Gaugin</option>
<option value="all"> - No Preference - </option>
</select></td>
<td><input name="qdid" type="hidden" value="'.$row['qdid'].'" />
<input name="submit" id="submit" type="submit" class="go" value="Update Quote Setting" />
</tr></form><table>';
}
function test(){
$vensel = $row['vendor'];
if($vensel = "Regent Seven Seas Cruises" ){ echo "selected" }
}//etc for each option
?>
Your code could use some redesign, but here's a suggestion to start: Make an array of your cruise lines, and iterate over that array to output the tags, and have your logic to determine which is selected in there.
$array = array('Regent Seven Seas Cruises', 'Silversea Cruises', 'etc');
foreach ($array as $cruise) {
echo "<option value=\"$cruise\"";
if ($row[vendor] == $cruise) echo ' selected="selected"';
echo ">$cruise</option>";
}
You're very close. Try calling test like this:
'<option value="Regent Seven Seas Cruises"'.test($row['vendor'],"Name of Cruise").'>Regent</option>'
and then implementing test like this:
function test($vensel,$cruisename){
if($vensel == $cruisename){
return "selected";
}
else
{
return "";
}
}
There are other ways to do this, but this way is the one requiring the fewest changes to your current code. The problem with your code is that variables have scope, and cannot be accessed outside of where they were created unless you pass them as parameters.
EDIT:
Here's another way to do it. Just put the below directly in the code, not inside a method. If you need to put it in a method, pass $row['vendor'] as a parameter.
$values = array('Regent Seven Seas Cruises','Silversea Cruises','Oceania Cruises','Windstar Cruises','Paul Gauguin Cruises','all');
$texts = array('Regent Seven Seas','Silversea','Oceania','Windstar','Paul Gauguin ',' - No Preference - ');
$len=min(count($values),count($texts));
for($i=0;$i<$len;$i++)
{
echo '<option value="' . $values[$i] . '"';
if($cruise == $row['vendor'])
{
echo ' selected';
}
echo '>';
echo $texts[$i];
echo '</option>';
}

Categories