retrieving multi valued select 'value' - php

Can anyone tell me how to get the 'value' of selected items from a multivalued select?
I have the following:
<select id="category" name="category[]" multiple="multiple">';
/* Select categories */
[...]
<option value"' . $row->id . '">' . $row->name . '</option>';
which would return:
<option value"1">itemName1</option>
Why is the code below giving me the selected text and not their values? What's wrong here?
$category = $_POST['category'];
if (count($category) > 0){
foreach ($category as $key => $value) {
echo $value . "<br>\n";
}
}
This is returning itemName1 and I need the actual value (1)
Thank you

Your HTML is invalid. You have:
<option value"1">itemName1</option>
while it should be:
<option value="1">itemName1</option>

mulple select will return a query like this (name = name and values = int)
name=1&name=4&name=99
so it return the selected values
the array would look like:
array(
name => array(
[0] => 1
[1] => 4
[2] => 99
)
)
ps if you fix the HTML error, you will most likely get a valid result

Related

Codeigniter in select option default value not working

Hi I am the beginner of Codeigniter. The following is my code. The issue is, it does not display the default value in select opinion menu. Please assist, Thank you.
<select name="taskOption1" class="form-control">
<option value="" disabled selected> -- select an option -- </option>
<?php
foreach($stagesData as $key => $value):
echo '<option value="'. $value -> stage_id . '"' .
set_select('taskOption1', $rows[0] -> stage_reject_id) . '>' . $value -> stage_name . '</option>';
endforeach;
?>
</select>
<select name="taskOption2" class="form-control">
<option value="" disabled selected> -- select an option -- </option>
<?php
foreach($rejectsData as $key => $value):
echo '<option value="'. $value -> reject_id . '"' .
set_select('taskOption2', $rows[0] -> stage_reject_id, ((($value -> reject_id) == ($rows[0] -> reject_id))?true:false)) . '>' . $value -> reject_name . '</option>';
endforeach;
?>
</select>
First of all, if you have a default option, I guess that should be the one selected? If so, you don't need <option value="" disabled selected> -- select an option -- </option>. But I may have understood this the wrong way.
Second, if you want to set a default value with set_select() in CodeIgniter, you must use the third parameter, like this:
set_select('taskOption1', $rows[0] -> stage_reject_id, TRUE)
You are using Form Helper, I see, so why don't you use from_dropdown or for multiple use form_multiselect
form_dropdown([$name = '', $options, $selected, $extra)
Parameters:
$name (string) – Field name
$options (array) – An associative array of options to be listed
$selected (string) – Selected Value
$extra (mixed) – Extra attributes
For your code
<?php $stagesData = ['' => '--select--'] + $stagesData; ?>
<?php echo form_dropdown('taskOption1', $stagesData, ''); ?>

Display data from database using explode in php

I have table named "test". I would like to retrieve data from one column. Each row have multiple data separate with coma. How can i display all the data of column in drop-down?
ID | Qualification
1 | BE,Phd,ME
2 | MCA,MBA
3 | MBA
How can i display all the data of Qualification column in dropdown? Output should be like following
BE
Phd
ME
MCA
MBA
MBA
Loop throught your rows and create an array of each row by exploding the rule. Then merge the arrays together. Something like this:
//Example data TODO: replace with your table data
$rows[0]['Qualification'] = 'a,b,c';
$rows[1]['Qualification'] = 'a,b,c';
$qualificationArray = array();
foreach($rows as $rowData)
{
$rowDataArray = explode(',',$rowData['Qualification']);
$qualificationArray = array_merge($qualificationArray,$rowDataArray);
}
Then use the qualificationArray to create an dropdown
echo '<select name="qualification">';
foreach($qualificationArray as $qualification)
{
echo '<option value="'.$qualification.'">'.$qualification.'</option>';
}
echo '</select>';
So the output of this is a dropdown of every value:
<select name="qualification">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
First off, read all the data from the database:
$quals = array(); // This is the array where we are going to store all the data.
if ($result = $db->query("SELECT * FROM `test`"))
{
while ($row = $result->fetch_assoc())
{
$quals[$row['ID']] = $row['Qualification'];
}
}
The rows are now stored in $quals in the form $quals[ID] = CommaSeperatedQualifications.
Next, create the drop-down by
Iterating through each element in $quals.
Separating the comma-separated list, Qualification into an array of elments, say $list.
Further iterating through $list and printing the <option>s of the drop-down.
For example:
// now create a drop-down
echo '<select name="list_of_quals">';
foreach ($quals as $id => $value)
{
$list = explode(',', $value);
foreach ($list as $item)
{
echo '<option value="' . $id . '">' . $item . '</option>';
}
}
echo '</select>';

Using foreach with mysqli_fetch_assoc

I have a mysql table with two columns; id and type. I'm trying to retrieve those values to use in a select list of values (aka drop down list). Outside of my html, this php works perfectly:
$sql = "SELECT * FROM `usertype`";
$query = mysqli_query($con, $sql);
while ($type_lov = mysqli_fetch_assoc($query)) {
echo '<pre>', print_r($type_lov,true), '</pre>';
};
Output from php above:
Array ( [id] => 1 [type] => System Admin )
Array ( [id] => 2 [type] => System Admin2 )
Array ( [id] => 3 [type] => System Admin3 )
Array ( [id] => 4 [type] => Account Admin )
Array ( [id] => 5 [type] => Account User )
To get it into the SELECT / OPTIONS tags, I attempted several things unsuccessfully. The two attempts that made the most sense to me (but that did not work) were:
<!--ATTEMPT 1-->
<select>
<?php while ($type_lov = mysqli_fetch_assoc($query)) {
foreach ($type_lov as $id=>$type) { ?>
<option value="<?php echo $id; ?>"><?php echo $type; ?></option>
<?php };
}; ?>
</select>
<!--ATTEMPT 2-->
<select>
<?php foreach ($type_lov = mysqli_fetch_assoc($query) as $id=>$type) { ?>
<option value="<?php echo $id; ?>"><?php echo $type; ?></option>
<?php }; ?>
</select>
Neither worked. What is the proper way to go about this?
You should read up on mysqli_fetch_assoc. It returns it's data as an associative array, meaning your table columns are used as indices for the array.
Furthermore, why are you coupling while with foreach in your first example? What's the thought process that you went on?
Anyway, this should help you on your journey:
<select>
<?php
while (($data = mysqli_fetch_assoc($query)))
{
echo '<option value="' . $data['id'] . '">' . $data['type'] . '</option>';
}
?>
</select>

Dynamically creating checkboxes

i am new to php.I want to dynamically create check boxes upon the result fetched from MySQL.If i have 10 records in employee Table so it must create 10 check boxes with employee name as value.I had seen several tutorials to make array of check boxes etc but could not fix the problem.Please anyone there to help!!!
Try this out:
<?php
//Create the query
$sql = "SELECT `name` FROM Employees";
//Run the query
$query_resource = mysql_query($sql);
//Iterate over the results that you've gotten from the database (hopefully MySQL)
while( $employee = mysql_fetch_assoc($query_resource) ):
?>
<span><?php echo $employee['name']; ?></span>
<input type="checkbox" name="employees[]" value="<?php echo $employee['name']; ?> /><br />
<?php endwhile; ?>
The example you see above relies on two things to actually function properly:
You're using MySQL
Your SQL-query must retrieve the employees' names (so that you can use them in the loop
MySQL is just a source of data. The same process would apply to making a checkbox list from ANY data source (array, file contents, database, etc...). A skeleton framework for the process would be:
$sql = "select idfield, namefield FROM sometable ...";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[]" value="{$row['namefield']}" /> {$row['namefield']}<br />
EOL;
}
Note that I've use the "name field"as you specified. But consider the case where you've got 2 or more John Smith's working for you - it is far more reliable to use the employee's ID number (whatever it may be in your database) than their name.
Lets say the result you fetched is in the $result array.
The array has 10 sub-arrays - each one looking like this:
[0] => array
['name'] => 'ZainShah'
[1] => array
['name'] => 'Stack'
The easiest way to do this is:
foreach ( $result as $key => $employee ) {
echo '<label for="employee' . $key . '">' . $employee['name'] . '</label>'
echo '<input type="checkbox" name="employee[]" id="employee' . $key . '" value="' . $employee['name'] . '" />';
}
I have made it easy to create checkboxes as well as radio buttons in any php form. Only thing is I am using Codeigniter MVC framework.
Here is the function definition that you can insert in your common-model or any helper file.
function createOptions($fieldName, $labelsArray=array(), $selectedOption, $fieldType,$valuesArray = array()) {
$returnString = '';
if(count($valuesArray)!=count($labelsArray))
$valuesArray=$lebelsArray;
if ($fieldType === 'checkbox') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='&nbsp&nbsp&nbsp<input type="checkbox" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if(in_array($valuesArray[$i], $selectedOption)){
$returnString.=' checked="checked" ';
}
$returnString.=' />&nbsp&nbsp<label>'.$labelsArray[$i].'</label>';
}
}
if ($fieldType === 'radio') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='&nbsp&nbsp<input type="radio" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if($valuesArray[$i]== $selectedOption)
$returnString.=' checked="checked" ';
$returnString.=' /><label>'.$labelsArray[$i].'</label>';
}
}
return $returnString;
}
And, you have to call this function in view file as,
<?php
echo $this->common_model->createOptions('userHobbies[]', $hobbyOptions, $userHobbies, 'checkbox'); ?>
First parameter is name of checkbox field or radio field, which is always gonna be same for all options for both cases. Second is labels array, Third is selected options which will show those options as checked while loading the form. Fourth is type of field that will be a string as 'checkbox' or 'radio'. Fifth will be values array, which, if present, will contain values for labels in the same order as that of labels. If its absent, labels array will be teated as values array
This is fairly straightforward. I'll assume that your MySQL result data is in an array called $employees, containing at least 2 elements: id and name. You mention that the "value" of the checkbox needs to be the name, but I'll assume that's what you want displayed in the HTML next to the checkbox. It would be better to have the "value" be the id of the database record for each employee (since employees might have the same name). Creating the HTML for the checkboxes is simply a matter of iterating through them with a foreach() loop, and creating a php variable to hold the HTML.
So, assuming your $employees array looks something like this:
[0] =>
'id' => '1'
'name' => 'Sam Jones'
[1] =>
'id' => '2'
'name' => 'Tom Smith'
[2] =>
'id' => '3'
'name' => 'Sarah Conners'
Just need to run through the array and create the output:
// init the var to hold the HTML
$output = '';
// cook the HTML
foreach ($employees AS $k=>$v) {
$output .= "<input type='checkbox' name='employee_array[]' value='" . $v['id'] . "'> " . $v['name'] . "<br />";
}
In your HTML form, just echo the $output variable. Notice that the ".=" operand is used to append to the $output variable I created. And the "name" of the form field ends in "[]". This will create an array named "employee_array" that gets passed back to PHP when the form is submitted. Each item that is checked becomes an element of that array, with its value being the ID of the employee record.
Hope that makes sense...
set echo in for loop you will always be able to set the loop variablenow simply echo/print the code

php multiple select drop down

here is my mysql and php code layout:
I have 3 tables
tableA stores unique "person" information
tableB stores unique "places" information
tableC stores not unique information about a person and places they have "beenTo".
here is how i layed out my form:
-one big form to insert into "person" tableA; "beenTo" tableC
in the form, a person mulitple selects "places" which get inserted into "beenTo"
my question is, when i am editing a "person" how do i display what the user has already selected to appear on my multiple select options drop down menu?
my drop down menu at the moment query "places" table and displays it in a multiple select drop down menu. its easier when a person have beenTo one place, the problem arrises when there is more than one "beenTo" places?
Foreach option, check if they have beenTo it. Then add the selected="selected" attribute to the tag if true.
Example:
<select multiple="multiple">
<option selected="selected">Rome</option>
<option>France</option>
<option selected="selected">Underpants</option>
</select>
And in PHP this might look like:
$beenTo = array("Rome","Underpants");
$places = array("Rome","France","Underpants");
?> <select multiple="multiple"> <?php
foreach($places as $place) {
echo "<option";
$found = false;
foreach($beenTo as $placeBeenTo) {
echo "value='$place'";
if ($placeBeenTo == $place) {
$found == true;
echo " selected=\"selected\" ";
break;
}
}
if (!$found) echo ">";
echo $place . "</option>";
}
?> </select> <?php
There's probably a much more efficient way to do this.
For clarification, you will want to have a name attribute for your select tag which allows for multiple selected options to function correctly.
<form method="post" action="">
<select name="places[]" multiple="multiple">
<?php
$_POST += array('places' => array());
$places = array('fr' => 'France', 'cn' => 'China', 'jp' => 'Japan');
$beenTo = array_flip($_POST['places']);
foreach ($places as $place => $place_label) {
$selected = isset($beenTo[$place]) ? ' selected="selected"' : '';
echo '<option value="' . $place . '"' . $selected . '>' . $place_label . '</option>';
}
?>
</select>
<input type="submit" value="Save Changes" />
</form>
<option id = 'example' <? if ($_POST['example']) echo 'selected' ?>>
But you'll be using a $_SERVER['cookies'] or other cache to store the past visits, not the $_POST array.. edit with extreme predjudice

Categories