I have:
$selectedItem = '100,200,300';
And mysql load:
<select multiple="multiple" name="product_id">
<?php
$query = mysql_query("SELECT * FROM products ORDER BY id");
while($row = mysql_fetch_array($query)){
echo '<option value="$row[id]">$name</option>';
}
?>
</select>
And I need $selectedItem (three values) to be:
<option value="$row[id]" selected>$row[id]</option>
How can I do that? I just can't find the solution when the selectedItem more than 1.
You should make your $selectedItem variable an array (and name it plural since it can have multiple values; just my added preference =P):
$selectedItems = array(100, 200, 300);
Doing this, you'll be able to check if the current row's id is in the array or not (with in_array()) and then "select" that row:
while($row = mysql_fetch_array($query)) {
$selected = in_array($row['id'], $selectedItems) ? ' selected="selected"' : '';
echo '<option value="' . $row[id] . '"' . $selected . '>' . $row['id'] . '</option>';
}
Alternatively, if you can't "define" your list of selected items as an array and you will only have a comma-separated string, you can use explode() to turn it into an array:
$selectedItems = explode(',', $selectedItem);
This will split the $selectedItem variable by commas into an array stored into $selectedItems (usable with the above code).
You can do it like this:
while($row = mysql_fetch_array($query)){
if ( str_pos( $selectedItem.',' , $row[id].',' ) !== false) {
$sel = 'selected';
} else {
$sel = '';
}
echo "<option value='$row[id]' $sel>$row[id]</option>";
}
Related
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);
}
I'm trying to add data from database to 2-dimensional array and then unpacking.
This function is in a folder named imsConnection.php
function getCurrency() {
global $cn;
$sql = "select * from Currency";
$res = mysqli_query($cn, $sql);
$a = array();
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_array($res)) {
$a[] = array($row['currencyID'], $row['currencyName']);
}
}
return $a;
}
And to unpack it into drop box:
<select name="drpCurrency" required>
<?php
require_once("imsConnection.php");
$a = getCurrency();
foreach($a as $i) {
echo "<option value='$i'>$a[$i]</option>";
}
?>
</select>
To make a formal answer: If you create multi dimentaion array and you loop with foreach you need to echo the value according the key you need. In you case:
foreach($a as $i)
echo "<option value='" . $i["currencyID"] ."'>" . $i['currencyName'] . "</option>";
I recommend you change your array do be according key - change the getCurrency function as:
while($row = mysqli_fetch_array($res)){
$a[$row['currencyID']] = $row['currencyName'];
Then you can use it as:
$a = getCurrency();
foreach($a as $k => $i)
echo "<option value='$k'>$i/option>";
Assuming you want the value as currency ID and the option content as the currency name
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>";
}
I keep getting array to string conversion in this code.. please help me
$qty_parse = oci_parse($conn, 'select qty from master_drawing');
oci_execute($qty_parse);
echo "<tr>\n";
foreach ($row as $item)
{
//echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES):" ")."</td>\n";
echo " <td>".($item);
if (is_numeric($item)){
$quantity = oci_fetch_array($qty_parse, OCI_ASSOC);
echo '/'.$quantity.'<meter value=10 min="2" max="10"></meter>';
}else {
echo ' ';
}
}
Looks like oci_fetch_array() returns array (array in function name should tell you something ;)).
You can use var_dump($quantity); to see what was returned by this function.
I guess that what you need to do is something like this: echo '/'.$quantity['qty'].'<meter value=10 min="2" max="10"></meter>';
First of all, your $row variable is not defined. You can use next solution:
$qty_parse = oci_parse($conn, 'select qty from master_drawing');
oci_execute($qty_parse);
while ($item = oci_fetch_array($qty_parse, OCI_ASSOC))
{
echo " <td>".($item['qty']);
if (is_numeric($item['qty'])){
echo '/'.$item['qty'].'<meter value=10 min="2" max="10"></meter>';
}else {
echo ' ';
}
}
P.S. When oci getting associated array via OCI_ASSOC - your script gets $item variable like:
$item['qty'] = 'value';
If you want to get value from $item as string variable, redefine you variable on loop like:
$item = current($item);
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.