I am a beginner trying to ouptut the values of dropdown menu from a database. I already automatically generate the values from database but the problem i am having is I want the the value that is being selected to be displayed.
Ideally im trying to update a Subject which I want to data to be displayed in an HTML page where each item could be updated. What i need is to be able to select the 'position' of the subject that is beeing selected.
Here is my code:
<p>Position:
<select name="position">
<?php
$sel_subject = get_all_subjects();
$subject_count = mysql_num_rows($sel_subject);
//$subject_count+1 because we are adding a subject
for($count=1; $count <= $subject_count+1; $count++) {
echo "<option value=\"{$count}\"";
if($sel_subject['position'] == $count) {
echo " selected='selected'";
}
echo ">{$count}</option>";
}
?>
</select>
You seem to be relying on $count to be some internal ID that remains static; given that it's just a monotonically advancing integer, this seems like a risky proposition. However, if you're comfortable with that, all you need to do is change the value in the last echo statement to be the subject name instead of $count. I would instead encourage you to use something meaningful to the database - for example, some people create an auto_increment field called subject_id and key off of that; others like to use UUIDs.
I would also generally suggest using a foreach loop instead of a for loop, as it tends to simplify the code (you don't have to worry about maintaining the counter, or creating fence post errors, etc.) Here's a brief example - I'm guessing a bit at what the actual data is that is available to you, hopefully you can extrapolate it to what you actually have.
<p>Position:
<select name="position">
<?php
$sel_subject = get_all_subjects();
foreach($sel_subject as $subject_num => $subject) {
echo '<option value="', $subject_num, '"';
if ($subject['selected']) {
echo 'selected="selected"';
}
echo '>', $subject['subject_name'], '</option>';
}
Related
I have a MySQL database that stores items (goods and services), and along with each item, terms (terms and conditions) will also be stored, which can be roughly 2000 bytes.
http://i.imgur.com/7t3cvSE.png
This is my basic set up
$term_options = array();
$term_options[] = "None";
$term_options[] = "massive string containing 2000 bytes or more";
...
foreach ($term_options as $term) {
?>
<label class="term">
<input type="radio" name="terms" value="<?php echo $term; ?>">
<?php echo $term; ?>
</label>
<?php
}
The above code does exactly what I want, but it feels wrong to have a massive value within a radio input (which may contain Unicode characters). Am I wrong to worry?
Before, I used a SELECT menu with option values equal to the index position of each array item:
?>
<select name="terms">
<?php
$i = 0;
for ($i = 0; $i < count($term_options); $i++) {
?>
<option><?php echo $i; ?></option>
<?php
}
?>
</select>
<?php
Then my $_POST would look something like this:
$terms = $term_options[$_POST['terms']];
It worked nicely until it came to my update form which should display the currently selected values. I wasn't sure how to compare the isset value with something generated via array.
It's simple to do this with static values, e.g.:
<option <?php if (isset($row['x']) && $row['x'] === 'x') echo 'selected'; ?>>x</option>
but while creating each option in a foreach loop, I have no idea what to do and the below doesn't work:
<option <?php if (isset($row['x']) && $row['x'] === $term_options[$i]) echo 'selected'; ?>><?php echo $i; ?></option>
$i++;
Yes, you are right in your worries. If this page is going to display many of these items and each item has a massive string like this, the final page is going to be huge. An this page will be sent by your server to the client browser. Bigger the page, bigger the time.
You are retrieving these items from a MySQL database. Each item probably has a primary key. Why don't you just use this primary key as part of the name of the radio buttons and then you may retrieve again just the selected item?
Something like
<input type="radio" name="rb_1">
where this "1" appended to "rb_" is the key of an item. Then you just need to break this string, recover the primary key and search if to recover the huge string.
This may generate another database operation, of course. But this will be nothing when compared with the transmission of a huge page with, say, 100 times 2k items.
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.
Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.
I have created and html form which have a drop down list.
This drop down list is populated from database.
<select name="classes">
<?php
foreach() {
?>
<option value="<?php echo $id ?>"><?php echo $name ?></option>
<?php
}
?>
</select>
Now I want to get the $id and $name both. How will I do this?
I have tried this
echo $_POST['classes'];
But it only displays the $id of the select item. And I want $id and $name both.
You can't. One possibility would be placing both infos inside the value attribute, and then separating them back again with php (by using a delimiter):
<option value="<?php echo $id.'|'.$name; ?>"><?php echo $name ?></option>
In PHP:
$datas = explode('|',$_POST['classes']);
$id = $datas[0];
$name = $datas[1];
But that's not how the system is meant to be. Usually the $name would be used only as a "friendly" info for the user, cause the value might sometimes just be an INT and user won't understand what that int refers to, so we give him a word description in order to choose an option: but what you would only care of is that value indeed, which you can always use to get again the description that comes along with it (by a search to the database, for ex.)
As far as I know, when you submit that form, only the value is going to be carried over. If there is no value then the inner HTML becomes the value.
What I'd do is:
<select name="classes">
<?php
foreach($classes as $id => $name) //i'm guessing here, is this what you meant?
{ ?>
<option value="<?php echo $id.'|'.$name ?>"><?php echo $name ?></option>
<?php } ?>
</select>
In case you are not familiar, the period is the concatenation operator. Think of it as glue for pieces of a string. So I'm gluing $id to the left of "pipe" and then gluing $name onto the end of that.
Then in your handler, use split or explode to separate the two values on the pipe.
Actually, I'd do it a little different, echoing more and going in and out of php/html less, but I tried to leave your code intact as much as possible.
append name to Id and pass it as value,,and explode name from the other end
You want is and name both so while storing option value ,
put like this
<option value="<?php echo $id."_".$name;?>"><?php echo $name?></option>
and on posting data just explode the value you will get both is and name
Sending form means only sending 'value' for select field (treat 'name' in option as a label only). You can simply fetch 'name' from database when you have 'id' while handling form submission.
I am contemplating taking the next step with my PHP applications and making the option fields dynamic. That would open the doors for more automation.
I have drop downs throughout my project, they are used to select a specific user and I update them manually when a new user is added (which is also a manual process). But if i take the first step and make these drop downs become populated by a MySQL Database, then i can move on to dynamic user creation.
I know how I can achieve this, but I am curious about some other alternatives (If there is any).
Here is what I would do..
$query = ** MySQL Select * From Database Query **
echo '<select name="usernames">';
while($row == mysql_fetch_array($query))
{
echo '<option>' . $row['username'] . '</option>';
}
echo '</select>';
So my questions is, would you do this differently? And why? Thanks!
What you are doing will work fine. I like to make it into a function so that if I ever need that dropdown on another page I dont have to write a lot of code over again.
function userDD()
{
$query = ** MySQL Select * From Database Query **
$html = '<select name="usernames">';
while($row == mysql_fetch_array($query))
{
$html .= '<option>' . $row['username'] . '</option>';
}
$html .= '</select>';
return $html;
}
This code does exactly what your code does except it doenst use echo. Instead you use a variable ($html) to store all of the data then when you are done you return it.
Your way is fine, but two things need to be changed:
- Run htmlentities() or htmlspecialchars() on all echoed HTML to avoid XSS. Unless you already sanitized it at database entry time but I find this practice silly.
- Add a value attribute to each <option> tag, otherwise you won't be able to retrieve the username selected. I suggest using the username's corresponding ID or something else that's unique to that user. If it's a string, use htmlentities/htmlspecialchars on it too.
php file
$users = getUsers();
include('template.tpl');
template
<select name="username">
<?php foreach( $users as $user ): ?>
<li><?= e( $user['username'] ) ?></li>
<?php endforeach; ?>
</select>
e is a function that escapes strings to prevent xss attacks
I wouldn't put an SQL query in the same document as my output...
I'd create a document containing all SQL queries, in functions, and include that file. Just to keep things seperated.