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>
Related
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 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.
This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];
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 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.