PHP - Update HTML Select list to show current value - php

I'm working on a simple HTML form that will include a drop down list for the selected Salesperson. The list is coming from a database and is in an array that is stored in a variable $ids and looks like this:
Array ( [John Jones] => JJ [Sally Smith] => SS [Victor Howards] => VH [Barnie Kemp] => BK )
Here's how the select list is currently constructed:
<?php
$output = "";
$selected = false;
foreach ($ids as $id => $value) {
$output .= "<option value=\"$value\"";
if ($id == $record->getField('initials')) {
$selected = true;
$output .= " selected";
$selectedID = $record->getField("id");
}
$output .= ">$id</option>";
}
if (!$selected) {
$chosen = $record->getField("initials");
$output = "<option value=\"$chosen\" selected>$chosen</option>$output";
}
echo $output;
?>
I'm trying to update the select list to show the current value for this field as the selected option. I have the name/value stored in these variables:
$initials
$name
So if $initials = 'SS' I would like Sally Smith to be the selected value in the list.

Try to use as simple as follow
<?php
$output = "";
foreach ($ids as $id => $value) {
$selected = "";
if ($id == $record->getField('initials')) {
$selected = "selected";
}
$output .= "<option value='$value' $selected>$id</option>";
}
echo $output;
?>

Do not make your code complex.. do it like this one:
$value=$record->getField('initials');
foreach ($ids as $id => $valueData) {
if($id==$value)
echo "<option value='".$id."' selected='selected' >$id</option>";
else
echo "<option value='".$id."'>$id</option>";
}

Related

How to keep the selected data in the select combo after the query?

I have this function that allows me to select a category (from a select combo) to associate with a product while I'm creating it. It works well but when I modify the product, I would like that the category assigned during creation, remain selected and visible at the beginning of the combo.
I suppose that i have to change something into the function when i update the product.
Any suggestion?
Thanks
Function:
function CategoryTree(&$output=null, $cat_parent_id=0, $indent=null){
global $con;
try {
// prepare select query
$query = "SELECT * FROM category WHERE cat_parent_id=:parentid AND cat_lang = '{$_SESSION['lang']}'";
$stmt = $con->prepare($query);
// this is the first question mark
$stmt->bindParam(2, $id);
// execute our query
$stmt->execute(array( 'parentid' => $cat_parent_id));
while($c = $stmt->fetch(PDO::FETCH_ASSOC)){
$disable= "";
if($cat_parent_id==0 ){
$disable= 'disabled="disabled" style="color:black;font-weight:bold;font-style:oblique"';
}
$output .= '<option '. $disable.' value=' . $c['cat_id'] . '>' . $indent . $c['cat_name'] . "</option>\n";
if($c['cat_id'] != $cat_parent_id){
CategoryTree($output, $c['cat_id'], $indent . " ");
}
}
// return the list of categories
return $output;
}
// show error
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
HTML:
<select name="category" class="form-control" id="category" required />
<option value="">Select a category</option>
<?php
echo CategoryTree();
?>
</select>
I think what you need (if I have understood your problem correctly) is to make use of the 'selected' attribute of the option you can say which option is marked as selected when the page loads by saying
'<option '. $disable.' value=' . $c['cat_id'] . ' selected>'
(https://www.w3schools.com/tags/att_option_selected.asp)
You can then use the value in the $_POST['category'] when the form is submitted and compare it to the category value ($c['cat_id']) in the loop to decide which element is selected.
When the form is submitted and the page reloaded then the last selected value will remain selected.
Forgive me if I haven't understood your question properly, but I THINK this is what you mean
Ok, I'll rewrite my question here, since I can't explain myself. I have to rewrite this code from the old mysql_ to PDO.
Perhaps by writing code directly it is better understood.
The main function:
/*
Generate combo box options containing the categories we have.
if $catId is set then that category is selected
*/
function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category WHERE cat_lang = '{$_SESSION['lang']}'
ORDER BY cat_id";
$result = dbQuery($sql);
$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;
if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}
// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];
$list .= "<optgroup label=\"$name\">";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}
$list .= ">{$child['name']}</option>\r\n";
}
$list .= "</optgroup>";
}
return $list;
}
Create.php:
$catId = (isset($_GET['catId']) && $_GET['catId'] > 0) ? $_GET['catId'] : 0;
$categoryList = buildCategoryOptions($catId);
and then
<select name="cboCategory" id="cboCategory" class="width-50">
<option value="" selected>-- Choose Category --</option>
<?php
echo $categoryList;
?>
</select>
update.php
// get category list
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;
if ($parentId == 0) {
$categories[$id] = array('name' => $name, 'children' => array());
} else {
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}
// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];
$list .= "<optgroup label=\"$name\">";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $cat_id) {
$list .= " selected";
}
$list .= ">{$child['name']}</option>";
}
$list .= "</optgroup>";
}
?>
and then
<select name="cboCategory" id="cboCategory" class="box">
<option value="" selected>-- Choose Category --</option>
<?php
echo $list;
?>
</select>
The functions are:
dbQuery() = global $dbConn;
$result = mysqli_query($dbConn, $sql) or die(mysqli_error($dbConn));
return $result;
dbFetchArray = function dbFetchArray($result, $resultType = MYSQL_NUM) {
return mysqli_fetch_array($result, $resultType);
}

Pass selected option value to mysql query

I have an html select that is filled with data from the database.
It looks like this
echo '<select name="client_list">';
foreach ($htmlselect as $key => $row) {
echo
'<option value='.$row->CUSTOMERCODE.'>'
.$row->CUSTOMERNAME. '</option>';
}
echo '</select>';
Below it I have a table that is populated with values from the DB.
$table = $wpdb->get_results('SELECT STRING, DATE, STRING02 FROM `CUSTOMERFILE` WHERE `code` = 2 AND `status` = 2');
echo '<thead ><tr >';
foreach ($header as $list) {
echo '<th >' . $list . '</th>';
}
echo "<thead></tr>";
if ( !empty( $table) ) {
foreach ( $table as $key => $value ) {
echo '<tr >';
foreach ( $value as $a ) {
if (empty($a)) {
# code...
echo '<td>NULL</td>';
} else {
echo '<td>' . $a . '</td>';
}
}
echo '</tr>';
}
}
Now in this query I want to add to the where another condition that takes the selected option value from the html select
It would look something like this
$table = $wpdb->get_results('SELECT STRING, DATE, STRING02 FROM `CUSTOMERFILE` WHERE `code` = 2 AND `status` = 2 **AND STRING05 = selected option value**');
How do I pass the selected value in the query?
The $wpdb->get_results() function take 2 parameters, the first is the query and the second is the output
$wpdb->get_results($command, $output);

How to echo specific value from associative array in <select> for Selected attribute

can anyone help me out for this thing
$person = array(‘abb’ => ‘Abbie, ‘abi’ => ‘Abigail’, ade’ => ‘Adelaide’);
$selection = '';
foreach ($selection as $abbreviation => $name) {
$selection = $selection."<option value=$abbreviation selected=(HOW DO I ECHO Abigail HERE FOR DEFAULT OPTION)>$name</option>";
}
try this
$person = array('abb' => 'Abbie', 'abi' => 'Abigail', 'ade' => 'Adelaide');
$selection = '<select>';
foreach ($person as $abbreviation => $name) {
$selection = $selection.'<option value="'.$abbreviation.'"';
if($name=='Abigail')
$selection .= 'selected';
$selection .= ">$name</option>";
}
$selection .= '</select>';
echo $selection;
if i understand right, this is what you want

"Array" is displaying in dropdown instead of values fetched from database

code snippet from html_form_class
<?php
$frmStr = $frm->addSelectList(
'city',
$city,
true,
'',
'--- Select City ---',
array(
'class' => 'dropdown-style5',
'id' => 'city'));
echo $frmStr; ?>
code snippet from seachcar.php
$city = $db->select('City','City_Name');
foreach($city as $row)
{
$row;
}
"Array" is displaying in dropdown instead of values fetched from database
Please Advice!
function addSelectList($name, $option_list, $bVal = true, $selected_value = NULL,
$header = NULL, $attr_ar = array() ) {
$str = "<select name=\"$name\"";
if ($attr_ar) {
$str .= $this->addAttributes( $attr_ar );
}
$str .= ">\n";
if ( isset($header) ) {
$str .= " <option value=\"\">$header</option>\n";
}
foreach ( $option_list as $val => $text ) {
$str .= $bVal? " <option value=\"$val\"": " <option";
if ( isset($selected_value) && ( $selected_value === $val || $selected_value === $text) ) {
$str .= $this->xhtml? ' selected="selected"': ' selected';
}
$str .= ">$text</option>\n";
}
$str .= "</select>";
return $str;
}
html output of addSelectList function is
<select name="city" class="dropdown-style5" id="city">
<option value="">--- Select City ---</option>
<option value="0">Array</option>
<option value="1">Array</option>
<option value="2">Array</option>
<option value="3">Array</option>
You need to rebuild the array of cities:
$city = $db->select('City','City_Name');
$city_rebuild = array();
foreach($city as $row) {
$city_rebuild[] = $row['City_Name'];
}
$city = $city_rebuild;
You do echo of array. Something is wrong in your abstraction objects. You must iterate on array to show up its values.
function addSelectList creates a "dropdown" (actually a select element)
You need to remove the html from the function output.
Edit 1
I was confused as to what you were going for. In your foreach($option_list... you need to know what keys are available in the $option_list array and what you want to appear in the select dropdown.

create a drop down list from a multi dimensional array

I have a multi dimensional array created from a mysql query. with each index holding an array containing customer information. I want to create a drop down list from this with the value being customer ID and the text being customer name but I don't know how to access the arrays inside the main array.
I have the following function which I used to create other drop down lists from single arrays but when I try to use it with a multi dimensional array all it returns is the index numbers. (i get a list of 0, 1, 2, 3)
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
$dropDown .= '<option value='.$value.'>'.$option.'</option>';
}
$dropDown .= '</select>';
return $dropDown;
}
EDIT
its 2 dimensional, an array holding arrays of customer details.
my query is ran on a different page so I save the results into a session variable with this.
$searchtext = $_POST['searchDB'];
$query = "SELECT * FROM customer WHERE First_Name LIKE '%$searchtext%'";
$data = mysql_query($query) or die(mysql_error());
$Customers = array();
while($row = mysql_fetch_assoc($data)){
$Customers[] = $row;
}
$anymatches = mysql_num_rows($data);
if ($anymatches != 0) {
$_SESSION['names']=$Customers;
}
print_r($array) gives me the following:
Array ( [0] => Array ( [ID] => 25 [First_Name] => Maggy [Surname] => barrows [Company_Name] => squiggle [Telephone] => 12121212 [Alt_Telephone] => 4343434 [notes] => ) )
Like that:
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
$dropDown .= '<option value='.$value['ID'].'>'.$value['First_Name'].' '.$value['Surname'].'</option>';
}
$dropDown .= '</select>';
return $dropDown;
}
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $option ) {
$dropDown .= '<option value="'.$option["name"].'">'.$option["name"].'</option>';
}
$dropDown .= '</select>';
return $dropDown;
}
Try something like the above replaceing "name" with the field name of what you want for the value and label
In your foreach, the $option => $value might be easier to understand as $key => $option. The $key is the index of the option, and the $option is the value you set.
If $value is a single-dimension array, you can just access its values by their indices ($option['id'] and $option['name'], for example).
If your options are single-dimensional, you can just access them with something like:
foreach($options as $option) {
$dropDown .= '<option value="' . $option['id'] . '">' . $option['name'] . '</option>';
}
Since you are dealing with a 2 dimensional array, or in other words one array nested within another you have to run another foreach loop like this:
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $customer) {
foreach($customer as $info) {
$dropDown .= '<option value='.$info["id"].'>'.$info["name"].'</option>';
}
}
$dropDown .= '</select>';
return $html;
}
I'm not sure what your actual indexes within your nested array are, so you may have to tweak the above code a little bit. Good luck!

Categories