Dropdowns not populating correctly with PHP foreach loop - php

I am currently populating a table with rows from a database. One of the columns is a dropdown that needs to be populated with multiple values.
Each dropdown is automatically defaulting to Bowling Green even if that row should not be Bowling Green. Most rows are either Southeast or Michigan but regardless of what it should be, it is defaulting to Bowling Green for some reason.
How can I have the dropdowns keep all values as options in the dropdown (bowling green, michigan, southeast), but have the dropdown value default to the value that it is in the database?
<?php
$sql = "SELECT TOP 100 *
FROM Table_OS_List
ORDER BY [CURRENT_SKU] ASC";
$drops = "SELECT [Purchasing_Group]
FROM Table_OS_List
GROUP BY [Purchasing_Group]";
$drop = $dbh->query($drops);
$allDrops = $drop->fetchAll();
?>
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows) {
?>
<tr class="row">
<td class="old_sku" id="old_sku"><?php echo intval ($rows['OLD_SKU'])?></td>
<td class="current_sku" id="current_sku"><?php echo intval ($rows['CURRENT_SKU'])?></td>
<td class="id" id="id" style="display: none;"><?php echo intval ($rows['ID'])?></td>
<td class="dropdown-select" id="purchgroup">
<select id="selected_group" class="selected_group" disabled>
<?php
foreach($allDrops as $dropdown) { ?>
<option class="choice"
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
<?php } ?>
</select>
</td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
<td><input type="button" class="delete" name="delete" id="<?php echo intval ($rows['ID'])?>" value="Delete"></td>
</tr>
<?php } ?>
Example of what it looks like now. You can see that it has multiple options which is what I need, but, regardless of it's value in the database, is defaulting to Bowling Green:

You need to add the selected attribute to the correct option.
Something like this:
<option class="choice"
<?php echo $row['Purchasing_Group'] == $dropdown['Purchasing_Group'] ? "selected" : ""; ?>
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
Where $row['Purchasing_Group'] is the column in the Table_OS_List table.
The important code here is <?php echo $row['Purchasing_Group'] == $dropdown['Purchasing_Group'] ? "selected" : ""; ?> - this is known as a Ternary, it could also be written in expanded form like this:
<?php
if($row['Purchasing_Group'] == $dropdown['Purchasing_Group']) {
echo "selected";
}
?>

You can add a selected attribute with a inline ternary operator just like so;
<option class="choice" <?php echo $dropdown['Purchasing_Group'] ? ' selected' : null ?> value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
and after you fetching all the datas from the DB, always good to check if result or results existing.

Related

Dynamic dropdown with auto select one option and it's sub-dropdown options

I have a dropdown in which one is for states and second one is it's sub category, which shows name of cities on basis of first dropdown.
Right now user need to select one category then subcategories load,
What change I want is "To set one value as default and load it's subcategories too" at load of page, and further user select different category so it should load it's subcategories accordingly.
Index.php:
<form name="insert" action="" method="post">
<table width="100%" height="117" border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%">
<select onChange="getdistrict(this.value);" name="state" id="state" class="form-control">
<option value="">Select</option>
<?php $query =
mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>">
<?php echo $row['StateName'];?>
</option>
<?php }?>
</select>
</td>
</tr><tr>
<th scope="row">District :</th>
<td>
<select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data: "state_id=" + val,
success: function (data) {
$("#district-list").html(data);
},
});
}
</script>
get_district.php:
<?php
require_once("config.php");
if(!empty($_POST["state_id"])){
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query)){
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>
You would need to do 2 things
1.) insert a selected flag into the input
2.) activate the second dropdown on page load
1.) If the selected entry does never change then hardcode the default selected field in your code like if $var = XXX then echo "selected".
If you have any function which calculates the default value e.g. a geolocation service like e.g. maxmind.com which takes the users remote IP address and outputs his current state, then use this result to set the selected entry.
<?php
while($row=mysqli_fetch_array($query)){
$row["StCode"] == "DESIRED_VALUE" ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> ><?php echo $row['StateName'];?>
</option>
[...]
Or add a field in the table SELECTED where you mark the default record with 1.
<?php
while($row=mysqli_fetch_array($query)){
$row["selected"] == 1 ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> >
<?php echo $row['StateName'];?>
</option>
[...]
2.) You have to set the second select dropdown on page load. There are several ways to do this - this is explained here in detail:
Jquery execute onchange event on onload

How to the get the correct value in drop down list during editing in codeiginiter?

My Problem is, I am saving one text field in the dropdown form.
During Editing, the exact value is not displaying in that text field area.
The first picture shows that I save the Praveen Kumar accounts and aravinth using droplist form...
the second pictures show, during editing I cannot retrieve the second name properly...
<?php foreach ($s as $r): ?>
<tbody>
<tr>
<td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
<td><select style="width:200px" class="form-control input-xs" data-width="100%"name="Tname[]">
<?php foreach ($query as $row ): ?>
<option value="<?=$row['name']?>"><?=$row['name']?></option>
<?php endforeach ?>
</select></td>
<td><input style="width:80px" type="text" name="TAmount[]" class="form-control input-xs price" value="<?=$r['TAmount'];?>"></td>
<td ><input style="width:50px" type="text" name="Per[]" id="amount" class="form-control input-xs amount" value="<?=$r['Per'];?>"></td>
<td><a href="javascript:void(0);" style="font-size:18px;" id="addMore" title="Add More Person"><span class="glyphicon glyphicon-plus"></td>
</tr><?php endforeach ?>
This is table code for editing...
this pname is used as a drop down list for that page.
please help me to solve the issues.
You never set your selected value, when you create your select options, you should check if the current option match the value of your result line name or PName.
<?php foreach ($query as $row ): ?>
<option value="<?=$row['name']?>" <?php echo ($r['PName'] == $row['name']) ? 'selected="selected"' : '' ?>><?=$row['name']?></option>
<?php endforeach ?>

Repitition of selected item in dropdownlist in PHP

I have this problem that the selected value in my dropdownlist is showing twice. What should i do so that it will show only once.
<td>
<select class="span8" style="width:100%" name="from_time[]" id="from_time<?php echo $count;?>" value="start_from" onchange="calculate_by_ajax(this.id);">
<option value="<?php
$start_from=$jobs_result['start_from'];
//$date_arr_to= explode(" ", $start_from);
//$date_to= $date_arr_to[0];
//$time_to= $date_arr_to[1];
$sec="SELECT DATE_FORMAT('$start_from', '%H:%i') as tp";
$sec_exe=mysql_query($sec);
$sec_res=mysql_fetch_array($sec_exe);
?>" selected="selected">
<?php echo $sec_res['tp']; ?></option>
<?php include("list.php"); ?>
</select>
</td>
Got it, instead of modifying one of the available options and marking it as selected, you actually add another option with your code.
You could change list.php to look like this (i.e. an array of all the times)
<?php
$drop_down_values = array('11:35', '11:36', '11:27');
?>
Then your code should look like this:
<?php
include("list.php");
$start_from=$jobs_result['start_from'];
$sec="SELECT DATE_FORMAT('$start_from', '%H:%i') as tp";
$sec_exe=mysql_query($sec);
$sec_res=mysql_fetch_array($sec_exe);
?>
<td>
<select class="span8" style="width:100%" name="from_time[]" id="from_time<?php echo $count;?>" value="start_from" onchange="calculate_by_ajax(this.id);">
<?php foreach ($drop_down_values as $value) {
if ($value == $sec_rec) {
echo "<option selected=\"selected\">$value</option>";
} else {
echo "<option>$value</option>";
}
}
?>
</select>
</td>

showing selected option from mysql in dropdown

I have a dropdown showing options from mysql, no problem there. The problem is on the update page when i want to show the option already selected previously.
The dropdown selects options from the margins table and puts the value into a field in the products table.
This is the query that selects the product record :
<?php
$recordID = $_GET["recordID"];
$product_result = mysqli_query($con,"SELECT * FROM products WHERE product_code='$recordID'") or die(mysqli_error($con));
$product = mysqli_fetch_array($product_result);
$checked_special = $product['product_special'];
$checked_publish = $product['product_publish'];
$checked_frontpage = $product['product_display_frontpage'];
$checked_facebook = $product['display_facebook'];
{
?>
And this is the part of the form that gets the options from the margins table and displays them on page.
<tr>
<td>Display Facebook</td>
<td><input type="checkbox" name="display_facebook" id="display_facebook" value="y" <?php if ($checked_facebook == 'y') echo 'checked'; ?> /></td>
<td><strong>Margin Group :</strong></td>
<td>
<select name="margin_group" id="margin_group"><?php
$resul2 = mysqli_query($con,"SELECT * FROM margins");
while($row2 = mysqli_fetch_array($resul2))
{
?> <option value="<?php echo $row2['margin_group']; ?>"> <?php echo $row2['margin_group']; ?></option>
<?php } ?> </select></td>
</tr>
How can i get the $product['margin_group'] value from the products table show as selected option in the dropdown, so that the user doesn't have to reselect every time they update the page.
Thanks :)
MsKazza
The idea is to add the word selected in the desired option tag like this :
<option value="x" selected>x</option>
This way it will be selected in the form Check this
in order to do that we will make a conditional statement for every option value in the while loop. If the value meets the condition, we will echo the word selected
<?php while($row2 = mysql_fetch_array($resul2): ?>
<option value="<?= $row2['margin_group']; ?>"
<?php if($row2['margin_group']) == $products_table_variable) : ?>
selected
<?php endif; ?>
><?= $row2['margin_group']; ?></option>
<?php endwhile ?>
<select name="margin_group" id="margin_group">
<?php
$datasource = mysqli_query($con,"SELECT * FROM margins");
while($getdata= mysql_fetch_array($$datasource)){
?>
<option value="<?=$row2['margin_group']?>" <?php if($getdata['colume_name']==$row2['margin_group']) echo "selected";?>> <?=$row2['margin_group']?></option>
<?php } ?>
</select>
Hope it will help you :)

In PHP, I have a table with repeating dropdowns but while multiple drops down lists are showing only the first is populated

I have a result-set that display many rows in a table, and in one of the table cells I'm adding a dropdown with options. The very first row of the table has a drop down that populates correctly with MySQL data, but in the rows below, while the drop down is indeed there, there's are no options in it. Thanks!
<?php while ($expenses = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo number_format($expenses["amount"], 2);?></td>
<td><?php //echo $expenses["vendor"];?></td>
<td><?php //echo $expenses["description"];?></td>
<!-- code for type dropdown-->
<td><select>
<?php while ($row = mysqli_fetch_assoc($type_result_set)) {
?>
<option value="<?php echo $row["type_name"];?>"><?php echo $row["type_name"];?></option>
<?php
}
?>
</td>
</select>
<!-- this section resumes table after drop down-->
<td><?php echo $expenses["department"];?></td>
<td><input name="done" type="checkbox" id="done"></td>
<td><textarea name="notes" id="notes"></textarea></td>
</tr>
<?php
}
?>
You have an error in your markup, make sure you close the <select> tag before the <td>
<td>
<select>
<?php while ($row = mysqli_fetch_assoc($type_result_set)) {?>
<option value="<?php echo $row["type_name"];?>"><?php echo $row["type_name"];?></option>
<?php}?>
</select>
</td>
You should put the data from $type_result_set in a array (using a while loop) before entering the $expenses = mysqli_fetch_assoc($result) loop. Once $type_result_set is looped through once, it won't give any more data, so you should store it beforehand.

Categories