select options to apply to different users - php

dropmenu is <select name="dropbox"> with 3 options - admin, activate, delete. The below snippet of code shows if the activate <option> is selected and submitted by the submit button then echo etc. I have a <select name="dropbox"> on every row for each user. My code only works if i change the last drop box.
if(isset($_POST['submit']))
{
if(isset($_POST['dropmenu']) && $_POST['dropmenu'] == 'activate')
{
echo 'is activated';
}
else{
echo 'fail';
}
}
Is there a way i can use foreach drop box with a value selected?

One of the possible ways is to connect the name of the select element with user id like
<select name="dropbox_[userId]">
In this case you simply know how to build an input name for checking it's value in $_POST table.
If you don't interate by users on submit code then you can use a regular expression to get an inforamtion abut user connected with element.

Related

If option value is not available in the select form, show error

Sorry if the title is not clear enough, here is the explaination :
I got a MYSQL Database named "perso", with "perso_name in it". The perso_name are the same as the values in my select form. Here is the HTML code :
<form method="post">
<select name="selectperso" onchange="showUser(this.value)">
<option value="op1">Option1</option>
<option value="op2">Option2</option>
</select>
<input type="submit" name="validperso" value="Confirm">
</form>
Here is the PHP code :
<?php
$error = 0;
if (isset($_POST['validperso'])) {
if ($error !== 0) {
echo"<script>alert(\"Error\")</script>"; }
else {
echo "<script>alert(\"Working\")</script>";
}
}
?>
Now, what i want to do is kinda tricky.
Let's say i have "op3" in my database, but the user can't have it. The problem is that the user can modify the value "op1" to "op3" and then he will have the op3. I want to make a condition which says "if the user select one of the "op" value available in the select, then it's ok. Else, error++."
Thanks for the help !
Okay, I write more info about your problem.
Usually what you need is called whitelisting - you create a list of some things, that are allowed for user.
It can be simple array like:
$allowed_options = ['op1','op2','op3'];
if (!in_array($userInput, $allowed_options)) {
// input not allowed, do something
}
Or more complicated logic like a query to mysql:
select * from table where option = "USER_INPUT" and user_role = 'SOME_ROLE'
Anyway, only you as a developer know how to limit user's activity.
If, for example, you create your select from array of values:
foreach ($values as $v) {
echo '<option value="' . $v . '">VALUE</option>";
}
Then use same array $values to check if user input is allowed.
Same to mysql queries or other ways of getting required content.
To achieve your target better way you bind user with options in DB (i.e. Like username and Password) and then every time you validate user and options.
Another way you can put a hidden field with correct option and user mapped. And every time you can matched user selected option with hidden field value. This is not secure method.

HTML Default Option in Select Using PHP Is Not Working

I'm bug-proofing a form that allows data editing for book entries in a database. Everything is working except for the drop-down box. The drop-down box automatically populates itself with every unique entry in a specific field in the database table, and that part works perfectly. However, when people click to edit a book all the fields are populated with that books information, and I wanted the drop-down box to default to the correct value for that book. My solution was to check each value as it populates the drop-down box against the actual book's value for that field and if they match, make it the "selected" value.
It is not working. The box is still populating fine, but it is not defaulting. Here is the code for the drop-down box.
<span style="margin-left:10px;">
Publication Type:
<select name="publicationType" >
<option value=""></option>
<option value="">-------------------------</option>
<?php
$lPub = '';
if(array_key_exists('publicationType',$_REQUEST)) $lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
if($pubStr == $bookArr['publicationType']){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
else{
echo '<option '.($lPub==$pubStr?'':'').'>'.$pubStr.'</option>'."\n";
}
}
?>
</select>
</span>
I can provide what all the variables are if needed. I don't see what I'm doing wrong, but maybe someone will be able to catch an obvious mistake.
Thank you,
Kai
Not sure this will help but try this:
<?php
$lPub = '';
if( array_key_exists('publicationType',$_REQUEST) )
$lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
I removed this condition:
f($pubStr == $bookArr['publicationType'])
since I didn't get what the $bookArr['publicationType'] is used for, perhaps you left it there by mistake

Two drop down list values auto selected based on php session value

I have two drop down lists.
Second one is populated based on value chosen in the first one. I'm using Double Combo Script Credit By JavaScript Kit to do that (I am very bad with javascript).
I use this to filter results from my Mysql database.
The problem is that when user applies filter i want him to see what he applied (when page refreshes or user goes to other page) - those values should be seen as selected in both drop down lists. I can't figure out where i should place an event or something else.
I'm holding subcategory values from the second drop down list in php session :
if (isset($_SESSION['subcat']) && !isset($_GET['subcat'])){
$color= $_SESSION['subcat'];
}
elseif (!isset($_SESSION['subcat']) && isset($_GET['subcat']))
{
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
elseif (isset($_SESSION['subcat']) && isset($_GET['subcat'])){
unset($_SESSION['subcat']);
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
else {
$color= "";
};
I can echo selected in first drop down list, based on session value and that works, but a second one drop down list is not generated when page refreshes and i don't know where should i echo 'selected = "selected"' or maybe everything can be done only with javascript? Please help.
The code:
<div class="filter">
<form method="get" name="doublecombo" action="" id="filterform" >
<select name="example" id="exampl" size="1" onChange="redirect(this.options.selectedIndex)">
<option>All kinds</option>
<option>Women</option>
<option>Men</option>
</select>
<select name="subcat" size="1" id="subcategory">
<option value="lists.php">All colors</option>
</select>
<input type="button" name="test" value="Filter" onClick="go()">
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("All colors","list.php")
group[1][0]=new Option("Pink","list.php?subcat=1 ")
group[1][1]=new Option("White","list.php?subcat=2")
group[1][2]=new Option("Green","list.php?subcat=3")
group[2][0]=new Option("Black","list.php?subcat=12")
group[2][1]=new Option("Blue","list.php?subcat=13")
group[2][2]=new Option("Grey","list.php?subcat=14")
group[2][3]=new Option("Brown","list.php?subcat=15")
var temp=document.doublecombo.subcat
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
</form></div>
you could set a cookie to hold the selected value, so if the user selects there choice and refreshes, you would then check if the cookie exists and then populate the menus accordingly.
Update:
This will store the selected values and repopulate the select menus if the user refreshes the page.
First select added onkeup:
<select name="example" id="exampl" size="1" onchange="redirect(this.options.selectedIndex)" onkeyup="redirect(this.options.selectedIndex)">
for the second select and as follows to check for changes
<select name="subcat" size="1" id="subcategory" onchange="checks(this)" onkeyup="checks(this)">
Now find the Line temp.options[0].selected=true and add this directaly below
createCookie("selected_option_1", x, 0);
if(x==0){
eraseCookie("selected_option_2");
}
then add these two new function say at the bottom of your script block
// checks if the Second Select has changed
function checks(oWhich){
createCookie("selected_option_2", oWhich.selectedIndex, 0);
}
// repopulate the options base on selection thats saved in the cookies
onload = function(){
if(readCookie("selected_option_1") != null) {
redirect(document.doublecombo.example.options.selectedIndex = readCookie("selected_option_1"));
if(readCookie("selected_option_2") != null) {
document.doublecombo.subcat.options.selectedIndex = readCookie("selected_option_2");
}
}
}
Finaly for these functions/scrip to work you will need
// The cookie script im using for the functions is located below include this and you chould ok. http://www.quirksmode.org/js/cookies.html#script
Now once the form has been submitted you GET the selected values as usual, and the REPOPULATE the menu, once you done with the cookie you could remove them.
If it's jQuery you are using you can try a short PHP tag on the page like this:
jQuery('#MyDropDown').val('<?php echo $_SESSION['MyStoredValue']; ?>');
If you are not using jQuery but straight JavaScript this would have the same effect:
document.getElementById("MyDropDown").value = '<?php echo $_SESSION['MyStoredValue']; ?>'

Problem With PHP/HTML Dropdown Box Code (selected value)

I wrote some PHP code that will allow me to create an html dropdown box, and then choose what should be the selected value. The code is:
$role_drop = "<select name='role'>";
$role_drop .= "\r\n<option value='Resident Assistant'>Resident Assistant</option>";
$role_drop .= "\r\n<option value='Community Assistant'>Community Assistant</option>";
$role_drop .= "\r\n<option value='Head RA'>Head RA</option>";
$role_drop .= "\r\n</select>";
$result = mysql_query("SELECT role FROM users");
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$role_drop = str_replace(">$role</option>", "selected=\"\" >$role</option>",$role_drop);
echo $role_drop;
}
}
In reality, this code has a bunch of HTML mixed in, but here is all of the PHP. When I run it, it seems to work. However, let's say the query returned 4 dropdown boxes with roles (from 4 users), and I were to Edit, or select, a new role for the 2nd dropdown box returned (with an UPDATE query), then when the page refreshes, all of the roles including and AFTER the dropdown box I updated will display their selected values as the new one I selected in the 2nd dropdown box.
And it's not that the values in the actual database are wrong, they are just displaying the wrong selected value. Here is the source code for the 3rd dropdown box after I select a new value for the second one:
<select name="role">
<option selected="" value="Resident Assistant">Resident Assistant</option>
<option value="Community Assistant">Community Assistant</option>
<option selected="" value="Head RA">Head RA</option>
</select>
So, it seems its selecting the correct value (Resident Assistant), however its ALSO selecting "Head RA", which is what I changed the prior dropdown box to.
It's very strange, and I have NO idea why this is happening. Any ideas?
Thanks!
It's because you're updating $role_drop each time, so all the previous changes are going to show up in subsequent dropdowns. I'd change the loop to something like this:
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$temp_role_drop = str_replace(">$role</option>", "selected=\"\">$role</option>", $role_drop);
echo $temp_role_drop;
}
}
That way you're not overwriting your original dropdown markup.
Nuts - forgot to escape my code. I meant, "It's just <OPTION VALUE="foo" SELECTED>".
Dunno if this helps, but according to the HTML spec you shouldn't be passing a value along with the SELECTED attribute of each OPTION. It's just .

'Remember' form drop list value when submitting to SELF?

I know how to 'remember' some form values whenever submitting the form to itself, in this case because of a picture upload function which requires the form to be submitted to itself. I simply want it so that if the user has filled out all fields and then uploads an image, the form doesn't get resetted (cleared).
I have solved this in regular fields and checkboxes like this:
<input type="text" name="headline" id="headline" value="<?php echo #$_POST['headline'];?>">
But how can I do this with drop lists? or radio buttons? There is no value option in a 'SELECT' list, even though I have tried writing in value anyways in the SELECT statement. Didn't work!
So, how can I set the SELECT (drop down lists) value with PHP (OR JAVASCRIPT) ?
If you need more input let me know, thanks!
For selects, you need to compare each option to your posted value, and handle it individually. Simply print out your options in a loop, and test each value against the value was was previously posted. If it maches, add selected to the attributes of that particular option.
$color = $_POST["colors"];
$colors = array("red","green","blue");
<select name="colors">
<?php foreach ($colors as $option) { ?>
<option<?php print ($option == $color) ? " selected" : ""; ?>>
<?php print $option; ?>
</option>
<?php } ?>
</select>
Actually, found out that it is possible to set the selectedIndex with javascript...
So I could put the selectedIndex in a hidden input before submitting the form, and then get that selectedIndex and set it with a javascript function... tricky but suits me better in this case...
document.getElementById("select").selectedIndex=nr;
Thanks though Jonathan!

Categories