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 .
Related
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.
I'm having a problem with the coding because I cannot get the chosen dropdown menu multi-select Version 1.4.2 to retrieve the previous selected subject value(s) from the dropdown menu when I click it again to activate it.
I'm using two different tables with one field name for each one, so I'm trying to match the t_subjects field name(s) in the member table with the name field name in the category table and if there is a match, that subjects field name will result in <option value='subject_name' selected >subject_name</option> and where there is no match it will be <option value='subject_name'>subject_name</option>
This is what I'm trying to get to happen for those subjects that match when I click it anytime after the first post.
There are forty-two subjects that are dynamically loaded in a chosen multi-select dd menu option.
I have no problem with posting the subject(s) names to the database using the implode method.
if(isset($_POST['submit']))
{
$subjects = implode(',', $_POST['subjects']);
But, if I open the page again to make another post with the subjects field name blank, I get an error that says:
Warning: implode() [function.implode]: Invalid arguments passed in...
So, you can see why I need to have the previous subject(s) values selected when I activate it again. Here is the code for the chosen dd menu.
<tr>
<td width="32%">Subjects:</td>
<td width="68%">
<input type="radio" name="utype" id="sutype" value="s" />Subject(s)
<div id="studspan" style="display:none;">
<strong style="vertical-align:top;">Select Subject(s) :</strong>
<select name="subjects" id="subjects" data-placeholder="Select Subject(s)" style="width:350px;" multiple class="chosen-select">
<?php
$cat_sele = mysql_query("SELECT * FROM category");
while ($cat_row=mysql_fetch_array($cat_sele)) {
if($_POST['subjects'] == $cat_row['name']) $s = " selected"; else $s = "";
echo "<option value='{$cat_row['name']}'$s>{$cat_row['name']}</option>";
}
?>
</select>
</div>
The problem seems to be in this part of the code: if($_POST['subjects'] == $cat_row['name']), because when I replace $_POST['subjects'] with 'Accounting' to check it, it will show that Accounting has been selected when I activate it again, but if I add another subject name, it will show all of the subjects as selected. I even tried if($_POST['t_subjects'] == $cat_row['name']) as well as ("SELECT name FROM category"), but they didn't work either. So any help to help this teacher make it work will be very appreciative.
I have also included other parts of the code that are involved in the process too.
elseif($_SESSION['user_type']=="m")
{
$getuser_sele = "select * from member where member_id = '".$_SESSION['ses_id']."'";
$getuser_qry = mysql_query($getuser_sele);
$getuser_row = mysql_fetch_array($getuser_qry);
$subjects = stripslashes($getuser_row['t_subjects']);
=============================================================
elseif($subjects=="" && $_SESSION['user_type']=="m")
{
$error="Please Enter Preferred Subjects";
}
=============================================================
elseif($_SESSION['user_type']=="m")
{
$qr=mysql_query("update member set
t_subjects='".addslashes($subjects)."',
=============================================================
<body onload="$('.chosen-select').show();
$('.chosen-select').chosen();">
=============================================================
<script type="text/javascript">
$("#sutype").click(function () {
$("#studspan").show(1000);
$('.chosen-select').chosen('destroy');
$('.chosen-select').show();
$('.chosen-select').chosen();
});
</script>
<script src="js/chosen.jquery.js" type="text/javascript"></script>
=============================================================
Update:
Tristan, it works but it shows all of the subject names as selected and de-seleted in the choice list, which is not what I want to happen. I also got the following error in the source code for each of the subject names. I'm just showing the first one below.
<b>Warning</b>: array_search() expects parameter 2 to be array, null given in <b>/home/.../.../edit.php</b> on line <b>2784</b><br /> <option value='Accounting' selected>Accounting</option><br />
I think the problem is how the table/fields are setup in the dbase.
Here is what should happen based upon the first row of the t_subjects. If I log in as member 1 and open the chosen dd menu, Accounting,Athletics,Art from row one of t_subjects should be selected while the rest of the subject list would be non selected in the chosen dd menu. This would happen for each member's row t_subjects they have listed when they initially posted them the first time.
all images to show what I'm talking about.
Using <select name="subjects" ... multiple> will only send post data for one selection. You need to use <select name="subjects[]" ... multiple> to send all selected options in the post data.
Then $_POST['subjects'] will be an array so you will need to search the array for the category name.
$cat_sele = mysql_query("SELECT * FROM category");
while ($cat_row=mysql_fetch_array($cat_sele)) {
if(array_search($cat_row['name'], $_POST['subjects']) !== false) $s = " selected"; else $s = "";
echo "<option value='{$cat_row['name']}'$s>{$cat_row['name']}</option>";
}
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
I am working on an existing wordpress website.
Users has field "user-country" (actually, I do not know how this field is created in wordpress, but it works).
In the registration form, user can choose one specific country.
However, now this country list is note defined "anywhere". It is created explicitly in the code:
<option value="Afghanistan" <?php if($current_user->user_country == 'Afghanistan') echo 'selected';?>>Afghanistan</option>
<option value="Albania" <?php if($current_user->user_country == 'Albania') echo 'selected';?>>Albania</option>
<option value="Algeria" <?php if($current_user->user_country == 'Algeria') echo 'selected';?>>Algeria</option>
<option value="American Samoa" <?php if($current_user->user_country == 'American Samoa') echo 'selected';?>>American Samoa</opt
etc.
The client wants to changed this list (from country to city). So i need to add other values. I do not want to write all values in the code. I would like to create some list with these values in wp-admin.
What is the best way to create a predefined values list? And these are not custom fields for posts.
EDIT:
I want to store values in DB, so admin can modidfy these values from wp-admin.
Actually, it is not so important whether it is DB or other option like XML.
I just want this list to appear as dropdown when user is registering and also to wp-admin to modify values of this list.
Also, a question come to my mind - is it a normal practice to store user custom fields like country or city in DB? Or maybe it is ok to define them in code explicitly?
Well, if you want the administrator to be able to modify the list, then DB is likely the best option here.
I would do something like this (in WordPress):
// put a default (initial) list in the database, if there isn't one there yet
if(!get_option('my_country_list')){
// store it as a |-delimited string, because WP serializes arrays,
// and this would be too much here
$data = 'Albania|Algeria|Disneyland|etc';
update_option('my_country_list', $data);
}
Now, later where you need that list, simply get it from the db:
$countries = get_option('my_country_list');
// turn it into an array
$countries = implode('|', $countries);
// generate the select field
$html = '';
foreach($countries as $country){
$checked = '';
if($current_user->user_country == $country)
$checked = 'selected="selected"';
$html .= sprintf('<option value="%1$s" %2$s> %1$s </option>', $country, $checked);
}
printf('<select> %s </select>', $html);
I guess you'll also have some kind of administration form for the options, where the administrator can modify entries from this list. This could be a textarea. When it gets submitted you update_option() again (replace new lines with |)
Thanking you for taking the time to look at this question.
The premise of the situation is that I have a "website" written in PHP and HTML that displays items from my database named "Spreadsheet." There are six columns, and over 4000+ rows of data. The columns are "accountID", "accountName", "website", "rating", "imageURL", "comments." The column "rating" in the website is a drop down list.
Currently, everything works well, but I have do questions:
How do I, with PHP, have data submitted to the database upon clicking on an option (such as "Very Bad") in the drop down list? At the moment, it requires the user to click a "submit" button, which refreshes the page entirely, losing their position. Is it possible to have it submit silently (without refreshing)
Second question has to do with the drop-down list again. How do you have the drop-down list display what's in the database? For example, if rating is "Very Bad" in the database, the drop-down list reflects that, and not what the first element is.
Below is my code.
". $row['website']."<br />
<Form Name =\"rating\" Method =\"POST\" ACTION =\"\" />
<input type = \"hidden\" name=accountID value=" . $row['accountID'] . ">
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\">Above Average</option>
</select>
<INPUT TYPE =\"Submit\" Name =\"formSubmit\" VALUE =\"Submit\">
if (isset($_POST['formSubmit'])){
$rating = $_POST['rating'];
$accountID = $_POST['accountID'];
var_dump($rating);
var_dump($accountID);
if(!mysql_query("UPDATE Spreadsheet SET rating='$rating' WHERE accountID='$accountID'")) {echo 1;}
}
mysql_close();
?>
Thanks so much! This question has been bothering me for a bit. I have tried many Google attempts, but I could not find an answer as specific as I am asking. Thank you so much.
Answer to #1:
You can use Javascript/AJAX to accomplish submitting the form without actually pressing submit. There are various javascript libraries that can help you accomplish this a lot easier than bare bones Javascript, namely jQuery ( http://jquery.com/ ). It's not a very complicated task but you will need to learn some basic Javascript and how to use jQuery. The essential flow of things would be when the form changes, submit an AJAX request to submit the form. You will need a second script to take the incoming AJAX request and do the save. Try search engines for some basic jQuery tutorials, and once you have a basic grip, something like "ajax submit on form change jquery" will get you started.
Answer to #2:
Something like this (please see my notes...)
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '">' . $row['option_name'] . '</option>';
}
echo '</select>';
If you would like the select preselected, that's pretty easy too! Taking from the last example:
$pre_selected = "Very Bad";
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '"';
if($row['option_name'] == $pre_selected) {
echo ' selected="selected"';
}
echo '>' . $row['option_name'] . '</option>';
}
echo '</select>';
But this is the part I'd like to point a few things out:
Don't use the old mySQL library like you are using and my examples are using. Please, use PDO, or at least mySQLi. The functions you are using are deprecated, and may not be available in PHP for much longer.
Please, escape your data properly. Search for "SQL Injection" and you will find a massive amount of information about how your code is very insecure (your UPDATE, specifically) because you did not escape the values.
Just a heads up, when/if you use jQuery, you're going to need to use id="foo" in addition to name="foo".
For the first question you can look at ajax onchange event. Basically when you change select value you fill call function that can call php file to insert data in db.
For the second question you check the DB for selected value and if it matches option value or text you set it to selected
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\"
<?php if($someValueFromDb=='Above Average'){
echo 'selected=selected';}?>
>Above Average</option>
</select>