POST selected name to database - php

I have a combobox which is populated from my database:
<select id="product" name="product">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
I am using the form method post to send the selected value to my database:
$product = $_POST['product'] ;
When I send the data to my database I only get the selected value in my database ('1', '2' or '3').
I also want to send the name of the selected option to my database ('One', 'Two' or 'Three').
Does someone know if it is possible to post the name of the selected value to the database?

It's not a good idea to do that. If you really need the text value in your server side script then you should obtain the text from the DB in the server side script.
If you are loading this combo box from the database and you defined properly your table keys, you shouldn't need to send back the text value of the field.
You need to define a key value for this data and use it for the 'value' of the field. If you don't have a key field in this table and you want to get the text value of the combo then you could use the text as a value in your combo and forget the value you are using now, but this is not recommended

You could use a hidden field, and update that field, on option change with JavaScript.
<input type="hidden" name="numberWritten" id="numberWritten" value="" />
JavaScript:
document.getElementById('product').onchange = function() {
var element = document.getElementById('product');
var otherValueFromOption = element[element.selectedIndex].innerHTML;
document.getElementById('numberWritten').value = otherValueFromOption;
}
You now have a $_POST['numberWritten']. With a value of either One Two or Three

When you use fields inside an HTML form, only the value of the fields gets sent.
My suggestion is that, on the script that receives the POST, you transform whatever you receive, into whatever you want to insert into the database, for instance using a switch statement or some other way of evaluating what was posted.
$value_to_insert = '';
switch($_POST['product']){
case '1':
$value_to_insert = 'One';
break;
case '2':
...
}
Another possibility would be to use the onChange of the select, to set the value of the selected item into a hidden input field, which will also go on the post.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>setvalue</title>
</head>
<body>
<script>
function setValue(sel){
document.getElementById('valueToPost').value = sel.options[sel.selectedIndex].text;
}
</script>
<form action="xpto.php" method="post">
<input type="text" id="valueToPost" name="valueToPost" value="One">
<select onchange="setValue(this)">
<option value="1" selected>One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
</body>
</html>
P.S.: change <input type="text" to <input type="hidden" to hide the field.

You would have to creat a dynamic variable that will changed based on user's selection.
I hope this helps
<?php
$product = $_POST['product'];
$productName;
if(product == 1){
$productName = 'One';
}
if(product == 2){
$productName = 'Two';
}
if(product == 3){
$productName = 'Three';
}
$insert = ("INSERT INTO table (product, productName) VALUES ('$product', '$productName')");
// query SQL to insert data..
//hope this is helpful
?>

There is a very tricky solution for this . If your drop-down is populated from Database , then replace my solution with the variable names. Use the following way :-
<select id="product" name="product">
<option value="One|1">One</option>
<option value="Two|2">Two</option>
<option value="Three|3">Three</option>
</select>
Now explode the $_POST['product'] with '|' at the time of database insert .

Related

PHP variable in header function in one drop list with two values [duplicate]

I'd like to post two values in one drop down option and I'm not sure about the best way to approach it.
The drop down list pulls data in from an external service. This data is 'id' and 'name'.
When I select an option in the drop down and then press submit I want the 'id' and the 'name' to be posted.
My code looks like this:
<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
<option value="<?php echo $name['id']);?>">
<?php echo $name['name']);?>
</option>
<?php endforeach; ?>
</select>
I've tried putting in a hidden input field, but that then doesn't render out the drop down (instead it just creates a list).
I am using both the id and name elsewhere, so I don't want to have to post just the id and then have to get the name again, hence I want to post both of them at the same time.
Any recommendations?
You cannot post two values unless both of them appear in the value attribute. You can place both in, separated by a comma or hyphen and explode() them apart in PHP:
// Place both values into the value attribute, separated by "-"
<option value="<?php echo $name['id'] . "-" . $name['name']);?>">
<?php echo $name['name']);?>
</option>
Receiving them in PHP
// split the contents of $_POST['data'] on a hyphen, returning at most two items
list($data_id, $data_name) = explode("-", $_POST['data'], 2);
echo "id: $data_id, name: $data_name";
You may add a hidden field with the name "id" and then bind an onchange event listener to the <select>. inside the onchange function, get the value of the <select> and assign it to the "id" field.
<form>
<select name="name" onchange="document.getElementById('id').value=this.value">
<!--
...
options
...
-->
</select>
<input type="hidden" name="id" id="id" />
<input type="submit" />
</form>
You could output something like:
<option value="<?php echo $name['id']."_".$name['name'];?>">
Then use preg_splitor explode to separate the two once the form data is processed.
The only way to do this is to include both pieces of information in the value for the single option. Just use code like the following, and then when you get the value back, split the string at the first underscore to separate out the values.
<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
<option value="<?php echo $name['id'] . "_" . $name['name']);?>">
<?php echo $name['name']);?>
</option>
<?php endforeach; ?>
</select>
Also, you could just leave the ID alone in your form, and then look up the id again when the user submits the form.
You could make as many hidden inputs as there are options, each with the name of one option value. The input's values are the contents of the options. In the second script, you can look for the dropdown value, and then take the value of the hidden input with that name.
We can pass it with data attribute, and can access in js,
<option value="<?php echo $name['id']);?>" data-name="<?php echo $name['name']);?>">One</OPTION>
var name = $(this).find(':selected').data('name');

php, get data from HTML select options, store them in variables and perform something

first, i've got a select option in a HTML document
<form action="Journey.php" method="post">
<select name = "Startpoint">
<optgroup label = "Start point">
<option value = "GrimesDyke">GrimesDyke</option>
<option value = "SeacroftRingRoad">SeacroftRingRoad</option>
<option value = "WykeBeck">WykeBeck</option>
<option value = "FfordeGrene">FfordeGrene</option>
<option value = "St.JamesHospital">St.JamesHospital</option>
.........
i determine the action is to pass the data using post method to Journey.php file in order to perform some algorithm, but when i click on the submit button in the browser it shown me my entire php code.... so i decided to run a few tests like this:
Journey.php
<?php
if(isset($_POST['submit'])){
$selected = $_POST['Startpoint']; // Storing Selected Value In Variable
echo "You have selected :" .$selected; // Displaying Selected Value
}
?>
this time, it displayed nothing, what i'm trying to do is, to store the Startpoint's value passed to the php file in a $selected variable and echo it on the screen, but it's still not working
i checked many examples online but honestly i can't see what i did wrong, please point out my mistake and show me how exactly i can make it right, thank you very much.
I wrote on php long time ago, but as I remember there is no 'submit' key in the $_POST table. Try to check for 'Startpoint' key instead.
This works for me:
<?php
if(isset($_POST['submit'])){
$selected = $_POST['startpoint']; // Storing Selected Value In Variable
echo "You have selected: " . $selected; // Displaying Selected Value
};
?>
<form action="" method="post">
<select name = "startpoint">
<optgroup label = "Start point">
<option value = "GrimesDyke">GrimesDyke</option>
<option value = "SeacroftRingRoad">SeacroftRingRoad</option>
<option value = "WykeBeck">WykeBeck</option>
<option value = "FfordeGrene">FfordeGrene</option>
<option value = "St.JamesHospital">St.JamesHospital</option>
<input type="submit" name="submit" value="Submit">
</form>

PHP Echo into textbox based on dropdown value

Im working on a small web application that follows a basic MVC pattern. currently i have data being pulled from a database into an array and im echoing out that value into one textbox (for now)
<input type="text" name="txtGasConRes" id="gasConRes" value="<?php echo $typical; ?>" disabled/>
The $typical value is being retrieved from my Model class into my Controller class and then echoed into the textbox for gas. I have a very similar textbox for Electricity.
My dropdown is as follows:
<select name="heatingType" id="heatingType" required>
<option value="" disabled selected>Select Your Option</option>
<option value = "Gas">Gas</option>
<option value = "Electricity">Electricity</option>
<option value = "Other">Other</option>
</select>
I was wondering if theres a way to determine where to echo the $typical value. So for example, If the user selected Gas as their heating type, then once the form was submitted it, the value would appear in the Gas textbox. If the user selected Electricity from the dropdown then the value would be echoed out into the Electricity textbox.
Any information will be appreciated.
Thanks!
This is definitely a job for JavaScript or jQuery if you prefer. You need to setup a handler to detect a change event on the select input. Once the user selects a value, then you can update the text field with text based on what the user has selected.
Not tested but something like this should work.
var select = document.getElementById('heatingType');
function updateTextField(selectedValue) {
switch(selectedValue){
case 'Gas':
return 'some text that you want in the text field';
break;
// etc.
}
}
select.addEventListener('change', function(){
var selectedValue = this.value,
textField = document.getElementById('gasConRes');
textField.value = updateTextField(selectedValue);
});
Create javascript function and put function in select box onchange event.(following code is working)
<script>
function heatingType(obj){
alert(obj.options[obj.selectedIndex].value); //if you want to show in alart
//or put in a variable
$x=obj.options[obj.selectedIndex].value;
}
</script>
<select name="heatingType" id="heatingType" onChange="heatingType(this)" required>
<option value="" disabled selected>Select Your Option</option>
<option value = "Gas">Gas</option>
<option value = "Electricity">Electricity</option>
<option value = "Other">Other</option>
</select>

getting the value in selection php

I have this selection box if I choose other textbox will show and the problem is the data I put in there only get the value "other" even I put text in the textbox the only value it gets is "other" so what do you suggest me to do this.
I'm using $_POST['talent'] to get the value.
Talent:
<select name="talent" onchange="if( this.value=='other' ) { this.form['other'].style.visibility='visible' }else { this.form['other'].style.visibility='hidden' };" required/>
<option value="Dancing">Dancing</option>
<option value="Singing">Singing</option>
<option value="other">Other</option>
<input type="text" name="other" style="visibility:hidden;" />
</select>
$_POST['talent'] will only return the value of the select element. If that value is 'other', that means that the user has selected that option. In that case, you need $_POST['other'] to get the value they typed into the box.
$talent = $_POST['talent'];
if ($talent === 'other')
$talent = $_POST['other'];
You'll need to use $_POST['other'] to get the contents of the text box. Also, you need to put the text box after the </select>.

Insert Listbox selected options to database NOT values

I'm implimenting a user registrations form for a college..There I need to calculate the fees and show it to the user and the same time need to insert to a database..
I have used a list box for like this
<select name="subject" id="select2"> ***(value=fees for the subject)
<option value="100">Arts</option>
<option value="150">English</option>
calculation is OK with the values wich are given(I used javascript calculation for that)
Now I want to insert the subject to database
ex:
INSERT INTO user(name, email, subject)
VALUES ('$_POST[name]','$_POST[email]','$_POST[subject]')");
I want to add the subject which selected to be add to database subject field as English not the fees.
I hope you can understand what I'm telling.Please Help
Thank You
Ideally you should use the labels as values like:
<select name="subject">
<option value="Arts">Arts</option>
<option value="English">English</option>
If for any reason you want to post both label and fee you can use hidden variables and JavaScript like:
<select name="subject_fee" id="subject_fee" onchange="populate_subject_name();">
<option value="100">Arts</option>
<option value="150">English</option>
</select>
<input type="hidden" name="subject_name" id="subject_name" value="">
<script type="text/javascript">
function populate_subject_name() {
var f = document.getElementById("subject_fee");
var n = document.getElementById("subject_name");
n.value = f.options[f.selectedIndex].text;
}
</script>
By the way I'd still recommend the first approach. There are other ways to calculate the fee -- just improvise. See this and this for one possibility.
This would require the server-side knowing the text of the SELECT element, as only the selected value is posted back.
It's possible in ASP.NET, as the SELECT element is know server-side. However I'm not sure if this in the case in PHP.
You have to add handle onsubmit event of form and a hidden field to preserve the selected text of list item.
<script type="text/javascript">
function submitIt()
{
var list=document.getElementById("select2");
var item=list.item(list.selectedIndex);
document.getElementById("subjectTest").value=item.text;
return true;
}
</script>
<form method="post" action="your_page.php" onsubmit="return submitIt()">
<input type="hidden" id="subjectTest" name="subjectText" />
<select name="subject" id="select2"> ***(value=fees for the subject)
<option value="100">Arts</option>
<option value="150">English</option>
<input type="submit" name="cmd" value="Submit"/>
</form>
In php, when you populate your list, keep in a map the value=>label mapping and get back the right value like :
$arr = array(100 => "Arts", 150 => "English");
echo $arr[$_POST[subject]]; //if $_POST[subject]==100, return "Arts"
Otherwise, in javascript, you can get it with
var index=document.getElementById("select2").selectedIndex;
document.getElementById("select2").options[index].text;
Then you can store it in an hidden input text...
Warning :
Don't insert directly the values in the sql request !
Be carful with injection SQL
Hope this help you...

Categories