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 |)
Related
I am new to stackoverflow and am after a little help. I have already tried searching for what I am about to ask, but cannot find any relevant topics, so here goes:
I have a PHP page, that gets a list of venues and it's town/city from a table within a MySQL database, which I have then concatenated to populate a dropdown, e.g. each <option> will display "[venue], [town/city]".
What I am trying to do is when the user selects one of the options, I want to store the [venue] and [town/city] as separate fields in another table within the MySQL database.
I would really appreciate any help.
More details might be needed. For instance do you need to know how to insert records on database? or are you also having trouble getting values of option tag?
But from what I understood:
First remember to set value attribute of option tags:
<option value="venue,town">venue,town</option>
Then after submitting the form, you can slice the returned string.
Assume you stored "venue,town" inside a variable named $str
$results = explode(",",$str);
$results will be an array with two elements. $results[0] contains "venue" and $results[1] contains "town"
I am not sure how much it helped but you can give more details and I'll get back
I think the best way is to put the datarecord ids (primary key value) into the value attribute of the <option> tags, then on the server side requery the data of the selected id from the database. This way your form can't be manipulated with unwanted data.
To be more clear, I would do it like in this simplified semi pseudocode:
<?php
$action = isset($_GET['action']) ? $_GET['action'] : null;
if($action == "save") {
$id = $_POST['venue'];
if(!empty($id)) {
/* fetch data belonging to $id from database and then save venue and town/city
as separate fields in another table */
}
}
/* fetch all data for the selectbox from the db and store it in $data */
?>
<form action="?action=save" method="post">
<select name="venue" size="1">
/* iterate through $data and create $id and $caption */
<option value="<?php echo $id; ?>"><?php echo $caption; ?></option>
/* iteration end */
</select>
<input type="submit" value="save" />
</form>
I am looking to populate a drop down field with a list of names from a database, and when an option is selected from that drop down, it will post all its values in the row, belonging to that chosen option.
This is probably hard to describe/understand, so to help illustrate, this is my table row:
I then proceed to populate the dropdown, and associate its value to whatever the selected option is posted
//////db_conx is db connection //////main_meal is table name
<form action="#" method="post">
<?php
$dropdown = $db_conx->query("SELECT * FROM main_meal") or die ("somethings broken");
while($array[] = $dropdown->fetch_object());
//echo '<option value ="'.$record['Mname'].'">'.$record['Mname'].'"</option>';
array_pop($array);
?>
<select name="changeCal">
<?php foreach($array as $option) :?>
<!--//get chosen value in drop down, and get its calories-->
<option value="<?php echo $option->calories;?>"><?php echo $option->Mname; ?></option>
<?php endforeach; ?>
</select>
This works great for one value, such as calories, in the above code, but I need more values.
For example, if choose Healthy egg and chips, the value will post 218, as the loop only associates calories and names at the moment.
I attempted various things, like this post:How to get multiple values from a single <select> variable in HTML/PHP?
But the foreach errors.
How can I something similar to what I have done, but store multiple values from one chosen option?
Thank you
Well, I think I understood your problem, but I think that the way you want to use is not usable, maybe I recommend that you put the id in the value of the option in the < select> and then with php you can get all the data from the data base.
For me that is the best way, but if you want do it like the example that you show, you can make an string, for example:
<option value="id:5_calories:258_protein:11g">Healthy eggs & Chips</option>
with your php should look like:
echo '<option value="id:'.$option->id.'_calories:'.$option->calories.'_protein:'.$option->protein.'">'.$option->Mname.'</option>';
you can make bigger the string with others values that you want to put.
In the backend when you send the select you can catch the data with a:
$myArray = explode("_", $_POST["changeCal"]);
Then you will get an array with values like:
$myArray[0]; // id:5
$myArray[1]; // calories:258
$myArray[2]; // protein:11g
Then if you need for example the calories you can make an explode like:
$calories = explode(":",$myArray[1]);
And you will have:
$calories[0]; //calories
$calories[1]; //258 <= Here are the calories.
Maybe if you want to do it of that way, this can be the easiest way, but I recommend send the ID.
Let me know if you need more help. Regards, Have a nice day.
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 have a form. The first field is a drop down select option. The user will select the name of a company. Based on the name a second drop down select option needs to be generated showing the addresses of all the company's branches.
The company data is stored in a mysql database.
How can I make the above happen?
If you are saying about <select> tag, the you can use this.
<select name="option">
<option value="one"<?php echo ($data["option"] == "one") ? ' selected="selected"' : ""; ?>>One</option>
<option value="two"<?php echo ($data["option"] == "two") ? ' selected="selected"' : ""; ?>>Two</option>
<option value="three"<?php echo ($data["option"] == "three") ? ' selected="selected"' : ""; ?>>Three</option>
</select>
For the sub select, see this demo: http://jsfiddle.net/ah4rx/
You have two options here
post the form on change of first dropdown and fetch the data based on posted value and display.
use ajax functionality to fetch the data based on value selected in dropdown and display
As basic as it gets - Send the company name via ajax to php, query the database to get the address, populate the next drop down in the same php script whilst in the loop and echo out. Receive back in ajax
I would use that code for the first generation of the first list. Then the second list would have to be done with AJAX (JQUERY can help you here).
You want JQUERY to get
var client=$('#client_name').find("option:selected");
Then make a normal AJAX request.
I would recomend you to use a PDO to connect to your databse instead of using that generic connection.
Based on the code that you posted in the reply to Vamsi then the code would be
<label>Client Name</label><br>
<select id="client_name">
<?php
// PDO connect to the DB
$db = new PDO ('mysql:host=localhost;dbname=DB_NAME','DB_USER','DB_PASS');
$sql = 'SELECT name FROM client'
$result = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
if(count($results)>0){ echo "<option></option>";}
foreach( $result as $key => $val)
{
// could also be $val['name'] depending on your db
echo "<option>".$key['name']."</option>";
}
?>
<select>
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 .