How to assign HTML form multiple selected options to PHP variable? - php

I have HTML form with multiple select element to let the users select multiple options from the list for submission. The form method is POST and it posts the form to PHP file. I figured it out how to echo multiple selected options through out reading this How to get multiple selected values of select box in php? but I am unable to write those values to a variable as string, and having space between each option-value. Is it possible to achieve this without using array?
Here is my HTML code:
<select name="place[]" id="place" multiple>
<optgroup label="Ottawa">
<option value="London">London</option>
<option value="Toronto">Toronto</option>
<option value="Windsor">Windsor</option>
</optgroup>
<optgroup label="Alberta">
<option value="Brooks">Brooks</option>
<option value="Calgary">Calgary</option>
<option value="Cold Lake">Cold Lake</option>
</optgroup>
</select>
Here is the PHP code:
<?php
foreach ($_GET['place'] as $selectedOption)
echo $selectedOption."\n";
?>
The above code only echo the values but not assigning it to variable as string. Can I simply use $locations = instead of echo?
Note: There are many Questions and Answers that shows how to assign select option value to PHP variable but not for multiple option.

Since you said you were using a post request, $_GET['place'] won't work. So using $_POST['place'] instead, you can glue the values of the array together using implode():
$locations = implode(' ', $_POST['place']);

Related

Select Random options from Select drop down

I want to be able to select randomly from the select tag using php,
i tried using rand(),it didnt seem to work
<select name="symbols" class="form-control" multiple="multiple">
<option value="BCH/BTC">BCH/BTC</option>
<option value="BCH/EUR">BCH/EUR</option>
<option value="BCH/GBP">BCH/GBP</option>
<option value="BTC-EOS">BTC/EOS</option>
<?php
$symbols = mysqli_real_escape_string($conn, $_POST['symbols']);
$rand001= shuffle($symbols);
?>
you have to use javascript for this,
because html has been created already before and php cannot change it:
in Jquery Syntax:
let options = $("option");
let toSelect = options[Math.floor(Math.random() * options.length)];
$(toSelect).attr("selected","selected");

Simplify retrieving the option values for an html dropdown into a php array

I'm trying to obtain the options for drop-down html menu's and put the choices into a php array.
The dropdowns contain numerical values, indiciating the top 3 preferences for text phrases, which will be included in an email.
I have a working model for doing it, but the code seems kind of klunky and I was wondering if there were s simpler way to do this?
I start off by creating the dropdown in html:
<div class="first_class">
<div class="left_col">
<p>
<select name="choice_2">
<option value="0" selected>_</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</p>
</div>
Then I get the drop-down values from $_POST and put them into an array
$choices = array('choice_2' => $_POST['choice_2']);
Then I use a switch statement to associate the $choices array values with the text phrase:
foreach ($choices as $key => $users_choice) {
if ($users_choice > 0) {
switch ($key) {
case "choice_2":
$choices_text[$choices_index++] = "This is the phrase the user selected as his choice"
break;
}
Now $choices_text is a new array with the text of the user's choices.
It works, but this seems like a really roundabout way to turn the options in the dropdown to a text phrase.
Am I missing something. Thanks for the help in advance.
Yeah bit clunky. You don't really need to reassign the post array or use a switch. What about just use the post value to index the text from your array of options? Eg
$text_you_want=$choices_text[$_POST['choice_2']];

PHP Multiple Hidden Values Select Option

Is it possible to assign multiple values to select option drop down lists? I need to retrieve multiple pieces of data from each drop down when they are selected and I have only been able to get the "name" and an "id". The name is displayed for the user to select however it is the ID that is passed to be processed. Here is my code:
<?php
$att_1 = $att_1;
mysql_connect("xx.xx.xx.xx","xxxxxx","xxxxxx");
mysql_select_db("dezanjow_cf");
$sql=mysql_query("select id, name from model");
if(mysql_num_rows($sql)){
$select= '<select name="model">';
$select.='<option value="default">Select Model</option>';
while($rs=mysql_fetch_array($sql)){
$select.='<option value="'.$rs['id'].'">'.$rs['name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
This produces html that looks like:
<select name="model">
<option value="default">Select Model</option>
<option value="5">GH20</option>
<option value="6">GH21</option>
<option value="7">GH22</option>
</select>
I wish to display them like this (as example):
<select name="model">
<option value="default">Select Model</option>
<option value="5","abc">GH20</option>
<option value="6","def">GH21</option>
<option value="7","ghi">GH22</option>
</select>
Thus when the data is passed onto the next php script, I can use both data "5" and "abc" when the user selects "GH20". I have not seen much on Google about this and don't even know if this is possible. Please let me know if I am asking for the impossible! Many Thanks, Nick
Hey you cannot have multiple values like that because post or get will return just first value which in this case is 5
<option value="5","abc">GH20</option>
but you can make your value looks like this
<option value="5,abc">GH20</option>
and then in php script you can separate values by using explode function
explode(',', $_POST['model'])
which will return array that you can use
array( 0=> 5, 1=>abc)
Its better if you serialize your data then at next php script unserialize it.
$data=array($rs['id'], "abc"); //data to be stored
$serialized_data=serialize($data); //serialize data
$select.='<option value="'.$serialized_data.'">'.$rs['name'].'</option>';
IMPORTANT
//unserialize information
$unserialized_data=unserialize($serialized_data);
this will output the same array array('SOMEID', "abc")

How to store multiple selected values from <select> tag in a single field [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed last year.
I have a select tag with multiple="multiple". And a user can select more than one value.
<label for="aoi">Area of Interest:</label>
<select id="sel_aoi" name="aoi" multiple="multiple">
<option value="hr-executive">HR Executives</option>
<option value="sr-manager">Sr. Manager</option>
<option value="service-advisor">Service Advisor</option>
<option value="production">Production Engineer</option>
<option value="mechanical">Mechanical Engineer</option>
</select>
How I can store these more than one selected values in single field of MySQL database?
Store it to an array and save the values to database using comma seprated.
<label for="aoi">Area of Interest:</label>
<select id="sel_aoi" name="aoi[]" multiple="multiple">
<option value="hr-executive">HR Executives</option>
<option value="sr-manager">Sr. Manager</option>
<option value="service-advisor">Service Advisor</option>
<option value="production">Production Engineer</option>
<option value="mechanical">Mechanical Engineer</option>
</select>
process.php
$aoi = implode(',', $_POST['aoi']);
When you get your values from your $_POST insert them in with a mysql insert multiple values like this:
insert into myTable
(someColumn, someOtherColumn)
values
(someValue1, someOtherValue1),
(someValue2, someOtherValue2),
(someValue3, someOtherValue3)
Edit: If you want the in one row use something like PHP implode():
$qry="insert into mytable (someColumn) values (".implode(',',$myArray).")
Not that you want to make sure that the $myArray variable is clean of anything that could SQJ Injection attack you database. A prepared statement would be a suggestion.
Django models come with JSONField() which you could use to serialize the list of integer values and later deserialize it into a list.
Another appproach is: if you have limited number of options, you could also try creating separate column for each option in your database instead of saving them in single field separated by comma.
E.g
interest_executive: Boolean
interest_manager: Boolean
interest_service_advisor: Boolean
Finally, another approach is to create a separate table and have foreign key relationship between user_id and interest_name_id but this would be overkill if you have limited number of interests.

Get Text From <option> Tag Using PHP

I want to get text inside the <option> tags as well as its value.
Example
<select name="make">
<option value="5"> Text </option>
</select>
I used $_POST['make']; and I get the value 5 but I want to get both value and the text.
How can I do it using PHP?
In order to get both the label and the value using just PHP, you need to have both arguments as part of the value.
For example:
<select name="make">
<option value="Text:5"> Text </option>
</select>
PHP Code
<?php
$parts = $_POST['make'];
$arr = explode(':', $parts);
print_r($arr);
Output:
Array(
[0] => 'Text',
[1] => 5
)
This is one way to do it.
What about this? I think it's the best solution because you have separated fields to each data. Only one hidden field which is updated at each change and avoids hardcoding mappings.
This inside HTML:
<select name='make' onchange="setTextField(this)">
<option value = '' selected> None </option>
<option value = '5'> Text 5 </option>
<option value = '7'> Text 7 </option>
<option value = '9'> Text 9 </option>
</select>
<input id="make_text" type = "hidden" name = "make_text" value = "" />
<script type="text/javascript">
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
This inside PHP:
<?php
$value = $_POST["make"];
$text = $_POST["make_text"];
?>
set the value of text to the value of the option tag, be it through static HTML markup or even if it's being generated by a server side script. You will only get the value attribute through POST
Another option however, on the server side, is to map the value ("5"), to an associative array, i.e.
<?php
$valueTextMap = array("5" => "Text");
$value = $_POST['make']; //equals 5
$text = $valueTextMap[$value]; //equals "Text"
?>
You'll need to include that Text in the value to begin with (e.g.: <option value="5_Text"> Text </option> and then parse, or...
You could use javascript on the page to submit the text as another parm in the POST action.
You can use simple dom
<?php
include('/mnt/sdb1/addons/simplehtmldom/simple_html_dom.php');
$html = file_get_html('tari.html');
$opt = array();
foreach($html->find('option') as $a) {
$opt[] = $a->value;
}
print_r($opt);
?>
I have always used a very elegant solution, similar to the ones already presented, which does not require a lot of additional code.
HTML
<select name="make">
<option value="1:First Option">First Option Text</option>
<option value="2:Second Option">Second Option Text</option>
<option value="3:Third Option Text">Third Option Text</option>
</select>
PHP
$value = split(':', $make)[0];
$text = split(':', $make)[1];
Benefits of this method
Yes, there are definitely similarities to serialworm's answer, yet we minimize the code in our PHP block by inconspicuously converting to an array and picking the element required right away.
In my case, I use this exact short-hand code in a contact form where this one-liner (to get the selected department name) is critical to keeping the code looking clean.

Categories