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.
Related
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.
For the life of me I cannot get this to work. I've looked at many articles on stackoverflow so if you could help that would be wonderful! I am working on a form submission for a client. They want to be able to select multiple values from a dropdown, which in turn I will pull from a database to get their query results.
<form id="test" action="results.php" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>
<?php
$query="SELECT City FROM Cities";
$result = mysqli_query($link, $query);
echo '<select name="city" id="city" multiple>';
while($r = mysqli_fetch_assoc($result)){
echo '<option value="'.$r['City'].'">'.$r['City'].'</option>'; }
?>
</select>
<input type="submit"/>
</form>
//results.php
$results=array();
$results[] = $_POST['role'];
$results[]= $_POST['city'];
echo "<pre>";
print_r($results);
echo "</pre>";
**How do I obtain all the values from the array and parse it into separate variables so I can use the variables in a SQL statement? Here is my output: **
Array
(
[0] => Array
(
[0] => Faculty
[1] => Alumni
)
[2] => Adams
)
Thanks so much for any help! :) And if there is a better way to do this, let me know.
[EDIT] : This code is wild open to SQL Injection , Please don't use it.
One submit options i already have in the question and one i created
dummy submit options for city, run this code in the different file,
than select different different options, and click on submit button,
to check how our query is getting built
Please read the note first and make sure you read the comment in the code, as they are more important than the code
Note 1-> in short you want to run the query, according to the selected options by the user,
make sure you read the comment to understand the logic, comments are more important than the code it's self,
Note 2-> and more thing i did not realize, you may be storing your value in different different table, if that's the case, code will change little bit, but basic shell will remain the same
Note 3-> To achieve the out come which you want to achieve, you basically have to create your query according to the set options, and than use IN keyword and you are good go,
Note 4-> I added echo statement, so you can see stage by stage how our query is developing, i added the comment, if you want see just remove the comment, I did not add the comment in the last echo so you can see the ready to use query string
Note Again-> one submit options i already have, one i created by my self, so you can see what happening, and you it going to work out for you.
as you said in the comment you may have 12 field, in your form, if that's the case, use this code, because lets say if you have to change
some thing in the future, and you have to change at tweleve places,
you will make mistake like miss some thing, or use the wrong variable
or some thing else, with this code, you have to change it one place,
and it will get apply to 12 or 24 places, number of places does not
matter,
and one more thing, it will better if you wrap this php code inside the function, the reason is lets say you have form on some other page, and you need same functionality only thing you have to do than, just call the function, and in the future if you have change some thing, just change the function code
I am giving you example on your code why it is better to wrap this in a function, lets say your table name are different than the given selected name in your form or you decided to hole values in different different table, than you have to change the code, if you wrote this twelve times or each form, and than you have to change it, than you are in big trouble, but if you use this code as function for different different form, you just have to do some changes in function or in here, and will get applied everywhere, in short chances of you screwing up some thing is just not their, so hope fully this will help you
SideNote -- one more thing i want to say, the reason this solution look big, is because of note, form and comment, if you count the php code line, with out the last echo statement, it actually only 10 lines of php code, so dont get afraid, becuase it's look big
<form id="test" action="" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>
<select id="city" name="city[]" multiple>
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="New York">New York</option>
</select>
<input type="submit">
</form>
<?php
//creating variable and saying all the post request is equal to this variable
$selected_options=$_POST;
foreach($selected_options as $key=>$option){
$countValue = count($option);
for($i=0; $i<$countValue; $i++){
/*
* start adding the value seperated by coma, remember again it going to
* be on extra coma so we have to remove it.
*/
$queryString_start_with_coma .= ",$option[$i]";
}
/*
* come out of loop, and now remove that extra coma
*/
$queryString_remove_extra_come= preg_replace("/,/", "", $queryString_start_with_coma, 1);
/*
* start building your query, use variable $key, just check the line below,
* you will understand where and why i am using variable $key.
*/
$query_string_with_and .= " AND $key IN($queryString_remove_extra_come)";
/*
* now unset the variable, this line is very important, so please also check
* your out come without this line,
* what i am simply doing is emptying the variable, if you dont
* do it, it will add the value in the existing value, which i dont want, what
* i want when the loop run for the second selected options, i want my variable
* to be empty, so i can create new string
* you will understand more if you remove this line and compare your two outcome
* Note: you dont have to unset if you dont want to, but you have empty the
* variable, you can also do by creating a empty string, do what ever you want
* to do, just make sure the variable is empty for the second loop
*/
unset($queryString_start);
}
$query_string_second_part_ready = preg_replace("/AND/", "", $query_string_with_and, 1);
//echo "$query_string_second_part_ready<br>";
$query_string= "SELECT * FROM table_name WHERE ".$query_string_second_part_ready;
//see how your query look like
echo $query_string;
It sounds like you want to be able to build a query based on the data submitted by the user. This may be a little more complex if you have multiple tables, but the basic idea is to use the input names with the fields, assemble the query from them, prepare the statement and bind the parameters.
Name the inputs the same as the database fields they match to
// Identify which database fields can be searched
// These names must match the names of the inputs
// Each name has a type which will be used later
$databaseFields = [ 'city' => 's', 'name' => 's', 'grade' => 'i' ];
$databaseFieldNames = array_keys($databaseFields);
// Set up the beginning of the query
$query = 'SELECT * FROM some_table WHERE ';
// Initialize an array to use to store fields to be searched
$where = [];
// Loop through all the post data
foreach ($_POST as $name => $value) {
// If the name is in the database fields list, add it to the query
if (in_array($name,$databaseFieldNames)) {
$where[] = $name;
}
}
// Add all the requested columns to the where
if (!empty($where)) {
$query .= ' '.$where[0].'=?';
array_pop($where);
foreach ($where as $name) {
if (is_array($_POST[$name])) {
// Use any to check for multiple possible values
$query .= ' AND '.$name.' = ANY (?)';
} else {
$query .= ' AND '.$name.'=?';
}
}
} else {
// Avoid an empty WHERE which will cause an error
$query .= ' TRUE';
}
$stmt = mysqli_prepare($query);
/* Bind parameters */
foreach ($where as $name) {
// $_POST should be validated here
if (is_array($_POST[$name])) {
// Arrays are imploded to work in an ANY
$value = "'".implode("','",addslashes($_POST[$name]))."'";
} else {
// Other values are used as sent
$value = $_POST[$name];
}
$type = $databaseFields[$name];
$stmt->bind_param($type,$value);
}
$stmt->execute();
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 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 |)
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.