How to delete duplicate value from drop down list - php

I have the following coding with the values in drop down list and I would like to delete the duplicated value from the list but I don't know how to do??
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
if ($fullNames==$_POST['dept']){
$selected="selected=\"selected\"";
}
else {
$selected="";
}
echo "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
?>
</select>
Existing result in $_POST['dept']
AC
HR
AC
Admin
MIS
MIS
Expecting result in $_POST['dept']
AC
Admin
HR
MIS

I have modified your script
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
$dropdown = array();
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
$selected="";
if($fullNames==$_POST['dept'])
$selected="selected=\"selected\"";
}
$dropdown[$fullNames] = "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
echo implode('',$dropdown);
?>
</select>
you can also fetch unique records in your query as you didn't posted query and updatiing your provided code.

Use DISTINCT on your SQL statement to get the unique result.
Example:
SELECT DISTINCT col FROM Table
You can read the details about SQL DISTINCT here : https://www.w3resource.com/sql/select-statement/queries-with-distinct-multiple-columns.php

Since it's in an array you can use
$array = array_unique($array);
this will automatically detect any duplicates and remove them leaving only the first instance in the array, see https://www.php.net/manual/en/function.array-unique.php
EDIT: I'm not 100% sure if I understand how your data is coming in, but if I am understanding it correctly you can try this:
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
$fullNames = array();
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
}
$fullNames = array_unique($fullNames);
if ($fullNames==$_POST['dept']){
$selected="selected=\"selected\"";
} else {
$selected="";
}
echo "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
?>
</select>
That said you probably don't want to be directly using $_POST['dept'] but rather will want to do some validation first on $_POST['dept'] then once you confirm it's a valid value then use it in a variable like this:
$dept = $_POST['dept'];
Then you would need to update the other code to use $dept rather than $_POST['dept']. But this will prevent any unintended consequences from a user submitting an invalid or worse yet a intentionally malformed dept. It is good practice to never trust or directly use user input but always test and validate it.

Maybe you can push names into an array with the current loop then filter out the duplicated values. Then use another loop to echo the tag.
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
$array = [];
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
array_push($array,$fullNames);//push all names into a array
}
$array = array_unique($array); //filter the duplicate names.
//another loop to echo the <option>
foreach ($array as $fullNames) {
if ($fullNames==$_POST['dept']){
$selected="selected=\"selected\"";
}
else {
$selected="";
}
echo "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
?>
</select>

Related

How do I use PDO prepared statements to build an array, and then use array to populate drop down list

I am using a script that I got from somewhere else that gives me an admin panel in my website.
This template utilises PDO, and I am not familiar with exactly how it works, and would like to learn more but have hit a dead end. I am trying to populate an array with usernames from my database, and then use the array to populate a drop down list on a webpage.
Here is my (attempted) code for the array:
function getUserList(){
$userList = array();
$sql = $this->connection->query("SELECT username FROM ".TBL_USERS);
$options="";
while($row = $sql->fetch()) {
$userList[$row['username']] = $row['username'];
}
return $userList;
}
and here mis my attempt to call the array into the drop down list:
<tr>
<td align="right"><label for="user">Username:</label></td>
<td align="left"><select name="user" id="user">
<option value="0" selected="selected">Username to Assign</option>
<?php echo $database->getUserList(); ?>
</select></td>
</tr>
Now there is a VERY good chance that what I have done is COMPLETELY incorrect but go easy on me LOL!
Your getUserList() method returns an array, not a string you can echo.
If you want to echo an option list of all elements in that array, you can either loop through the result in your view:
foreach ($database->getUserList() as $key => $value)
{
echo '<option value="' . $key . '">' . $value . '</option>';
}
Or you do it in the method (probably another method that takes the array and returns the list).

Create special dynamic select

I want to do the next thing but I don't know how to do this, I'll try to explain me
I have an field generated by php code like this (Works)
<select id="profiles_select" name="profiles_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['profile']);?>">
<?php echo strtoupper($system['profile']);?></option>
<?php
} while($system = mysql_fetch_assoc($r)); //the "$r" it's the query
$rows = mysql_num_rows($r);
if($rows > 0) {
mysql_data_seek($r, 0);
$systemas = mysql_fetch_assoc($r);
}
?>
</select>
The query
<?php
$q="SELECT DISTINCT profile FROM sys_profiles";
$r=mysql_query($q,$ConecLocal) or die(mysql_error());;
$systemas=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
What I need?
I need generate another similar to first generated by php code but, this time I need made a Query including the value of the first , something like this:
<?php
$value_select=$_GET['profiles_select'];
$q2="SELECT DISTINCT systems FROM sys_profiles where profile=$value_select";
$r2=mysql_query($q,$ConecLocal) or die(mysql_error());;
$profiles2=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
Next of the query I need show in the another the query result, something similar to the first select (generated by php), but do the query when the first of the it's selected
<select id="systems_select" name="system_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['systems']);?>">
<?php echo strtoupper($profiles2['systems']);?></option>
<?php
} while($profiles2 = mysql_fetch_assoc($r2)); //the "$r2" it's the another query
$rows2 = mysql_num_rows($r2);
if($rows2 > 0) {
mysql_data_seek($r2, 0);
$systemas = mysql_fetch_assoc($r2);
}
?>
</select>
Thanks for the help.

php array for each in for each

I am trying to get a select list with values from $staff
The bit i am struggling is selecting the staff that are already enrolled from $entry->enrolments.
If the $staff id exists in $entry->enrolments select it in the select list
$entry = Record from mysql
$staff = list of staff in an array.
$entry->enrolments = comma seperated values of enrolled staff
<select name="tutor[]" id="tutor" multiple="multiple" size="5" class="required" title="Select Staff">
<?php
$entry = get_record("staff_development", "id", $id);
$staff = get_records("user", "deleted", "0", "lastname ASC", "id,firstname,lastname,idnumber");
$sdenrolments=array($entry->enrolments);
$people = explode(",", $entry->enrolments);
foreach($staff as $tutor){
foreach($people as $person){
if($tutor->id>1)echo '<option value="'.$tutor->id.'"';
if ($person==$tutor->id) {echo 'selected="selected"';}
echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}
}
?>
</select>
Any help/guidance would be greatly appreciated.
Thanks in advance
in_array is the easiest way to tell if a value is in an array :) Replace your loops with this:
foreach($staff as $tutor){
echo '<option value="'.$tutor->id.'"';
if(in_array($tutor->id, $people))
echo 'selected="selected"';
echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}
You might also want to rename your variable from people to enrolled_staff or something a bit more clear.
Your if block is confusing. You are checking for $tutor->id > 1 when opening the option tag, but aren't when closing it. PaulP.R.O mentions in_array which you should replace your foreach loops with. Here is your if block cleaned up and set the check for selection inline.
if($tutor->id > 1) {
echo '<option value="'.$tutor->id.'" ' . (($person==$tutor->id) ? ' selected="selected"': '') . '>';
echo $tutor->lastname.' '.$tutor->firstname;
echo '</option>';
}

While loop only executing once

I have a form that displays contact email addresses in text boxes, and drop down selections for titles for those corresponding emails.
TitleSelect1 Email1
TitleSelect2 Email2 ....
the emails have a title_id set, and the select list selects the existing Title. This works fine for the first contact, but the rest will only display the email address, the title dropdown is empty.
<?php
while ($row2 = mysql_fetch_array($Contact_list)) {
?>
<tr>
<td align="right"><select id="Contacts_title" name="Contacts_title[]">
<?
while ($row3 = mysql_fetch_array($title_list)) { //put the contact titles into an array
if ($row3['title_id'] == $row2['title_id']) {
?>
<option value="<? echo $row3['title_id'] ?>" selected="true"><? echo $row3['title'] ?>!</option>';
<?
}
else {
?>
<option value="<? echo $row3['title_id'] ?>"><? echo $row3['title'] ?> </option>';
<?
}
}
?>
</select>
</td>
<td align="left"><input type="text" id="Contacts" name="Contacts[]" value="<? echo $row2['email'] ?>"/></td>
</tr>
<?
$count++;
}
mysql_fetch_array() only goes through the results of a given query once. Since you're not executing the title_list query every time though your contact list loop, it's still at the end of the query results when you start every iteration after the first.
What you need to do is take all the results from your title_list query, put them into an array, and iterate over that for each of your contacts.
Here's a general example of how you'd do this (with extraneous bits trimmed out):
$contact_list = //some query
$title_list = //some query
$titles = array();
while($title_ar = mysql_fetch_array($title_list)) {
$titles[] = $title_ar;
}
while($contact_ar = mysql_fetch_array($contact_list)) {
// some stuff
foreach($titles as $title) {
// do something with each title
}
}
you should put the rows in a variable and echo that after the while loop.
once the inner while loop executes once fully, you wont get any more values in that mysql_fetch_array call again. Since the cursor reached the end of rows.
You should store the results of the inner while loop into a php array and then iterate through this array every time within the inner while loop.

Prepare drop down list and use multiple times

I've got a database of regions for sale and I'm displaying it in a table for admins to edit the cost, whether it's for sale and who's selling it (seller). For the seller I've got a drop down list with an first option as the current owner for ease of use and then under that I just want it to list the rest of the possible users that could be sellers.
Thing is, there's a good 200 regions and I don't want to loop through every user for each region to display them in a list. Is there a way I can prepare the many 's rather than loop every time. Something like preparing the list as a string then inserting it as HTML? Wouldn't know how to do it that way if possibe.
Thanks in advance.[
let's say you make your list this way:
$str = "<select>";
$result = mysql_query("select * from sellers");
while($row=mysql_fetch_assoc($result)){
$str.= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
$str.="";
And you just output that everywhere you want the list to appear.
Also, you don't have to put the one you want selected by default at the top, you can also add the word 'selected' to the option tag like so:
<option value='1' selected>John Doe</option>
If I understand the question correctly. You need to create an array of option tags.
$Name = array();
$q = "SELECT name FROM users";
$r = mysqli_query ($dbc, $q) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($r)){
$Name[] = "<option value='$row[\"name\"]'>$row[\"name\"]</option>";
}
Then anytime you need that you just loop through array like so:
<select id='thisselect' name='thisselect'>
<?php
foreach($Name as $key =>$line){
echo "$line";
}
?>
</select>
All the answers are good but I suggest you to separate the logic from the content itself, instead of doing all that with concatenated strings, you should do it like this:
<select id="region" name="region">
<?php foreach($regions as $key => $region) ?>
<option value="<?php echo $key ?>"><?php echo $region ?></option>
<?php endforeach; ?>
</select>

Categories