Distinguishing multiple items in a select multiple with PHP - php

I have a form on my website where one can select multiple other editors for a post.
The list of qualified editors is echoed by PHP, which works. But when multiple are selected HTML makes it into one list of the ids. F.E. If Jay (id = 4) and Sam (id = 9) are selected. The received value will be $_POST['editors'] = 49.
My code:
<select multiple class="editors" name="editors" id="editors">
<?php
//Gebruikers ophalen
$editorArr = getEditors();
foreach($editorArr as $editor){
echo "<option value='".$editor['id']."'>".$editor['email'].' - '.$editor['type']."</option>";
}
?>
</select>
and the handling PHP
$editors = htmlentities($_POST['editors']);

Okay! Try this:
<select class="editors" name="editors[]" id="editors" multiple>
<?php
//Gebruikers ophalen
$editorArr = getEditors();
foreach ($editorArr as $editor) {
echo "<option value='".$editor['id']."'>".$editor['email'].' - '.$editor['type']."</option>";
}
?>
</select>
The name should be an array so it can treat all selected values separately.
Hope it helps

Related

when one dropdown list selected i want to change other dropdown lists unselected

I want to do like i said on the question.
This i the main part . When i select any options from that select part . i want to make other select blocks' element unselected.
Assume i have more select blocks for search for year, month, day etc.
Can you help e how i can do that.
<select id="makale" size="4"name="formMakale"style="height:7em;width:16em;border:0px;outline:0px;fontsize:16px;padding-left:10px;" >
<?php
$authorsQuery = $hb->authors();
foreach($authorsQuery as $v){
echo '<option value="'.$v->id.'">'.$v->name.' - '.count($hb>aticlesbyauthor($v),1000).' yazi</option>';}
?>
</select>
for example my other select block is:
if this block was selected before the upper select block, once select block with id makale is selected, make the block with id kategoriSec unselected if it is selected as i said before.
Thank you.
<select id="kategoriSec" size="4" name="formCat"style="height:7em;width:16em;border:0px;outline:0px;fontsize:16px;padding-left:10px;" >
<?php
$catQuery = $hb->db->get_results("SELECT * FROM category");
foreach ($catQuery as $v) {
echo '<option value="'.$v->id.'">'.$v->name.'</option>';
}
?>
</select>
You can use jQuery on change event to do this. First check the 2nd select box is empty or not then set the value to null when you select from the first select box.
$("#makale").on('change', function(){
if($('#kategoriSec').val() != ''){
$('#kategoriSec').val(null);
}
});
visit the below link for an example. this example may help you.
https://jsfiddle.net/skpaul82/87h5y0dm/5/

How do I store id of items selected from dropdown box inside an array?

I need to store all the items selected from a dropdown box inside array. I have only one form now with the select dropdown list. So each time I select an item from the list and submit the form it overwrites the previous item.
How do I make it work like each time it submits the id will be stored so that I can display all the items selected?
//this is the select dropdown for addon item
<select name="addon">
<?php
mysql_select_db($database_bumi_conn, $bumi_conn);
$query="SELECT * FROM tbl_addons WHERE status=1";
$result=mysql_query($query)or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$a_id=$row['addOns_id'];
$a=$row['addOns'];
?>
<option value="<?php echo $a_id?>"><?php echo $a;?></option>
<?php
}
?>
</select>
//And this is how I store the id
$addon_id=$_POST['addon'];
//edited with session
$_SESSION['option']=array();
$_SESSION['option'][$addon_id]=array('qty'=>$qty,'date_1'=>$date_1,'date_2'=>$date_2);
print_r($_SESSION['option']);
foreach($_SESSION['option'] as $option=>$value)
{
echo $option.'=>';
foreach($value as $val)
{
echo $val;
}
}
You could use SESSION' variables to store all the ID :
session_start();
// Rest of your code here
// $addon_id=$_POST['addon']; Becomes :
if (!in_array($_POST['addon'], $_SESSION['addons']))
$_SESSION['addons'][] = $_POST['addon'];
Edit: Not sure about your edit with sessions. You're resetting $_SESSION['option'] everytime, losing previous addon_id values
Ignoring the fact that you're using a deprecated, inherently un-secure and unmaintained extension, you need to use the multiple attribute on your <select> element and let PHP know that it will be receiving an array of values by using the [] suffix on the element name. To summarise...
<select name="addon[]" multiple>
<?php foreach($collection as $val => $label) : ?>
<option value="<?= htmlspecialchars($val) ?>"><?= htmlspecialchars($label) ?></option>
<?php endforeach ?>
</select>
The PHP variable $_POST['addon'] will then contain an array of selected values (when the form is posted of course).

submit all users values from form into db

This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];

dynamic html select boxes need to update mysql

Ok, so this one is a little confusing. I have select dropdowns that are produced by PHP. It can be 4 selects, or 30 select dropdowns. Then there's option values. Here's what I have so far
<?php while($row = mysql_fetch_assoc($notes)){ ?>
<select name="milestone" id="milestone[<?php echo $row['id']; ?>]">
<option value="Enrollment Date">Enrollment Date</option>
<option value="Discharge Date">Discharge Date</option>
<option value="A/C Start">A/C Start</option>
<option value="Completion Date">Completion Date</option>
</select>
<?php } ?>
If I have 4 select boxes, I might have arrays as follows: milestone[2134], milestone[2222], milestone[225], and milestone[1022]
The array number is the id of the mysql table entry I need to update with the value of that specific select dropdown. I was thinking maybe to use milestone[][id] and loop through that?
Any ideas since there might be 20 select dropdowns?
Thanks!
do you want to fetch the values of your options from the database as well as the id ? Then you should to mysql_fetch_array or mysql_fetch_object function instead of mysql_fetch_assoc. This function only returns the number of the results while the two above returns the number as well as values.
Got it!
First, I had to apply the array to the name of the select like so and set the id value:
<select name="milestone[]" class="mstones" id="<?php echo $row['session_id']; ?>">
Then, with jquery, looped through the class and created created an array with the value being something I can "explode" in php:
var milestoneVal = [];
$("select.mstones").each(function(i, selected){
milestoneVal[i] = this.getAttribute('id') + ':' + $(selected).val();
});
Then, simple PHP
foreach($_POST['milestone'] as $v){
$m=explode(':',$v);
//db insert
}
It was tricky, and I'm sure there's a cleaner solution, but it works for me! Sorry for the poor initial explanation, and hope this helps someone else.

Generate Select List for Each Group of Records with the Same Value

I am using the array below to echo a HTML select box but I haven't been able to figure out how to do the loop using the unique values:
sid evid
13 1
14 1
15 2
16 3
I am trying to loop through the above array by the unique values stored in 'evid' so I can create a select box which groups by 'evid'. At the moment, my loop produces 4 select boxes when it should only produce 3. sid 13 and 14 is outputting a select box each since my code isn't grouping them but I just can't get my head around how I get these two values to group during the loop.
Anyone have any suggestions?
EDIT
Code I'm using:
<?php while ($s = mysql_fetch_array($sessions)){ ?>
<?php foreach ($evs as $ev){
if ($ev['evid'] == $s['evid']){
?>
<form action="" method="">
<fieldset>
<ul>
<li>
<label></label>
<select name="sessions[]">
<option name="sessions[]" value="<?php echo $s['sid']; ?>"><?php echo $s['sname']; ?></option>
</select>
</li>
</ul>
</fieldset>
</form>
<?php } // end if match ?>
<?php } // end foreach ?>
<?php } // end while ?>
If I understand well what you need, and assuming the arrays are sorted, have a try with:
$sid = array(13, 14, 15, 16);
$evid = array(1, 1, 2, 3);
$current_evid = $evid[0];
echo "<select .....>\n";
for ($i=0; $i<count($evid); $i++) {
if ($current_evid != $evid[$i]) {
echo "</select>\n";
echo "<select ...>\n";
$current_evid = $evid[$i];
}
echo "<option value=".$sid[$i].".....\n";
}
echo "</select>\n";
output:
<select .....>
<option value=13.....
<option value=14.....
</select>
<select ...>
<option value=15.....
</select>
<select ...>
<option value=16.....
</select>
Feed your array into array_unique()
Try using PHP's array_unique - details here: http://php.net/function.array-unique
Or - if you're using something like MySQL to get the data, try using GROUP BY or DISTINCT in your SELECT statement.
EDIT per comment:
If you want/need to keep your original array, just copy the array, and use array_unique on the copy. Then, use the copy to create the select dropdown.
Alternate solutoin:
Keep a $values_written array.
In your loop, before you write the <option>, check that it's value is not already in the $values_written (using PHP's in_array - details here)
Then write the <option>.
Then add it's value to the array (using PHP's array_push - details here)

Categories