How to add values of generated textbox in database using mysqli - php

This code somehow stores only the value of last textbox. When we generate 3 textboxes, only the value of 3rd is stored in database instead of all. I want to store all the generated textbox values in the database
<?php if(isset($_POST['submit'])){
$num_cat = $_POST['num_cat'];
$text = $_POST['category'];
foreach ($text as $key) {
// echo $key."\n";
}
$insertquery = mysqli_query($con, "INSERT INTO accounts (accountusername, accountemail) VALUES('".$num_cat."', '".$key."')");
if(!$insertquery){
echo "Error".mysqli_error($con);
}
} ?>
<script type="text/javascript">
//when the webpage has loaded do this
$(document).ready(function() {
//if the value within the dropdown box has changed then run this code
$('#num_cat').change(function(){
//get the number of fields required from the dropdown box
var num = $('#num_cat').val();
var i = 0; //integer variable for 'for' loop
var textboxes = ''; //string variable for html code for fields
//loop through to add the number of fields specified
for (i=1;i<=num;i++) {
//concatinate number of fields to a variable
textboxes += 'Category'+i+': <input type="text" name="category[]' + i + '" placeholder = "category_' + i + '" /><br/>';
}
//insert this html code into the div with id catList
$('#catList').html(textboxes);
});
});
</script>
<form method="post" action="">
Number of fields required:
<select id="num_cat" name="num_cat">
<option value="0">- SELECT -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="catList"></div>
<input type="submit" name="submit" value="Submit"/>
</form>

If you update your javascript to write this (remove ' + i + ' from the name):
textboxes += 'Category'+i+': <input type="text" name="category[]" placeholder = "category_' + i + '" /><br/>';
then $_POST['category'] will be an array. It then depends how you want to store the values, but assuming you'll want three rows, you'll need to do this:
foreach ($_POST['category'] as $key) {
$insertquery = mysqli_query($con, "INSERT INTO accounts (accountusername, accountemail) VALUES('".$num_cat."', '".$key."')");
if(!$insertquery){
echo "Error".mysqli_error($con);
}
}
This is explained in the PHP manual.
Please have a look at how can I prevent SQL-injection in PHP? as well, because your current code is vulnerable to simple exploits.

Related

Get the Value First Before the Form Shows up PHP

I'd like to show up to 10 email fields to submit on the form but only by selecting options from 1 - 10.
<form action="" method="post" name="select">
<select name="row">
<option value=1">1</option>
...
<option value="10">10</option
<input type="submit" name="select">
</form>
The next form shows up depending on the selected form
<form name="secondform">
<?php ... ?> <!--for loop depending on the value above-->
<input name="email>
</form>
So you have your dropdown, submit that value to either self or another php script that contains this:
$selected = $_POST['select'];
for($i = 0; $i<$selected; $i++){
echo "<input type='text' name='email$i'>";
}
$selected is the value of the dropdown menu.
Now we have a for loop. It set's $i to zero then says while $i is less than the value of your drop down value, add 1 more to $i and run echo "<input type='text' name='email$i'>";
As you can see, I appended $i to to email so that each field has it's own unique name.
What you can do as well is do just as CP510 says and add onchange='this.form.submit()' to the select tag so it is submitted automatically and I would submit the form to the same page. This meaning set the action of the form of which the select menu is in to action="<?php echo $_SERVER['PHP_SELF']; ?>".
I would STRONGLY recommend learning jQuery for something like this.
Here's the jQuery (mostly just plain javascript) version of this... it's very similar:
Please make sure you put this in the head of your html file:
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
HTML:
<select id='selected' onchange='addFields();'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
</select>
Javascript:
function addFields(){
var selected = $('#selected').val();
for(var i = 0; i<selected; i++){
document.write('<input type="text" name="email' + i + '">');
}
}

PHP code to get selected text of a combo box

I have a combo box named "Make". In that combo box I'm loading vehicle manufacturer names. When I click SEARCH button I want to display the selected manufacturer name. Below is part of my HTML code.
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" >
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="submit" name="search" value="Search"/>
Below is my PHP code so far I've done.
<?php
if(isset($_POST['search']))
{
$maker = mysql_real_escape_string($_POST['Make']);
echo $maker;
}
?>
If I select Toyota from the combo box and press SEARCH button, I'm getting the answer as '2' . It means it gives me the value of the 'Toyota'. But I want to display the name 'Toyota'. How can I do that? Please help me ....
Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']
<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['Make']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
echo $maker;
}
?>
Put whatever you want to send to PHP in the value attribute.
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="--Any--">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You can also omit the value attribute. It defaults to using the text.
If you don't want to change the HTML, you can put an array in your PHP to translate the values:
$makes = array(2 => 'Toyota',
3 => 'Nissan');
$maker = $makes[$_POST['Make']];
You can achive this with creating new array:
<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");
if (isset ($_POST['search'])) {
$maker = mysql_real_escape_string($_POST['Make']);
echo $array[$maker];
}
?>
if you fetching it from database then
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>
Change your select box options value:
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="Any">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You cann't get the text of selected option in php. it will give only the value of selected option.
EDITED:
<select id="cmbMake" name="Make" >
<option value="0">Select Manufacturer</option>
<option value="1_Any">--Any--</option>
<option value="2_Toyota">Toyota</option>
<option value="3_Nissan">Nissan</option>
</select>
ON php file:
$maker = mysql_real_escape_string($_POST['Make']);
$maker = explode("_",$maker);
echo $maker[1]; //give the Toyota
echo $maker[0]; //give the key 2
you can make a jQuery onChange event to get the text from the combobox when the user select one of them:
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$('#EvaluationName').val(str);
})
.change();
</script>
When you select an option, it will save the text in an Input hidde
<input type="hidden" id="EvaluationName" name="EvaluationName" value="<?= $Evaluation ?>" />
After that, when you submit the form, just catch up the value of the input
$Evaluation = $_REQUEST['EvaluationName'];
Then you can do wathever you want with the text, for instance save it in a session variable and send it to other page. etc.
I agree with Ajeesh, but there are simpler ways to do this...
if ($maker == "2") { }
or
if ($maker == 2) { }
Why am I not returning a "Toyota" value? Because the "Toyota" choice in the Selection Box would have already returned "2", which, would indicate that the selected Manufacturer in the Selection Box would be Toyota.
How would the user know if the value is equal to the Toyota selection in the Selection Box? In between my example code's brackets, you would put $maker = "Toyota" then echo $maker, or create a new string, like so: $maketwo = "Toyota" then you can echo $makertwo (I much prefer creating a new string, rather than overwriting $maker's original value.)
If the user selects "Nissan", will the example code take care of that as well..? Yes, and no. While "Toyota" would return value "2", "Nissan" would instead return value "3". The current set value that the example code is looking for is "2", which means that if the user selects "Nissan", which represents value "3", then presses "Search", the example code would not be executed. You can easily change the code to check for value "3", or value "1", which represents "--Any--".
What if the user clicks "Search" while the Selection Box is set to "Select Manufacturer"? How can I prevent them from doing so? To prevent them from proceeding any further, change the set value of the example code to "0", and in between the brackets, you may place your code, then after that, add return;, which terminates all execution of any further code within the function / statement.

Dynamic Form Submission to database

I've got an HTML form that has some static fields and some fields that are dynamically added with javascript. It looks sort of like this
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="t_' + i + '" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
when the user clicks it adds a text box field. How does the data stored into the database.Kindly suggest me an idea what are the resources used to do this .Thanks in advance
Good day Shashak
In order to submit the data of your form into the database, regardless of the javascript of the form the data should be passed using in your case the POST method to a script 'connection.php' in your case.
This script should contain a way to connect to your database followed by the logic that will validate your data and then at the end if the validation is successful a database query that will INSERT the data into your database.
Which is your level of understanding when it comes to PHP or any other server-side scripting language and databases? - I will be able to give you more information if I know what you know.
I think instead of giving the textbox the name format t_1 , t_2 you can give it as an array like below
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="txt_name[]" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
PHP
It will post data like this:
Suppose you select option 2.
$inputs = $_REQUEST['t']; // change the name like this name[]
$textarea = $_REQUEST['textarea'];
$selectbox = $_REQUEST['select']; // you should define the name of the select box as i used 'select'
insert into mysql
$conn = mysql_connect('localhost', 'db user', 'db password');
mysql_select_db('database name');
for($i=0; i<count($inputs); $i++) {
$sql = "insert into <table name> (textarea, inputs) values ($inputs[$i], $textarea)";
mysql_query($sql);
}
it will store each row as per your selection of input text boxes.
Note: Modify the query as per your requirement.

differentiating identical select names

how can I differentiate the 'select name' of 'f1' and 'f2' currently both named 'subcat' while still having only 1 subcat variable? this code works accurately only if cat value=2, if cat value=1 then subcat value always =0
<?php
$cat=$_POST['cat'];
$subcat = $_POST['subcat'];
?>
<form action='submitsite.php' method='POST'>
<table>
<tr>
<td>category(optional)</td>
<td>
<select name='cat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "1">music </option>
<option value = "2">film </option>
</select>
<div id = "f1" style="display:none">
<select name='subcat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "3">pop</option>
<option value = "4">rock </option>
</select>
</div>
<div id = "f2" style="display:none">
<select name='subcat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "5">comedy</option>
<option value = "6">drama</option>
</select>
</div>
</form>
</div>
<script type = "text/javascript">
function showForm(){
var selopt = document.getElementById("opts").value;
if (selopt == 1) {
document.getElementById("f1").style.display="block";
document.getElementById("f2").style.display="none";
}
if (selopt == 2) {
document.getElementById("f2").style.display="block";
document.getElementById("f1").style.display="none";
}
}
</script>
Add [] to the name. The selects will then be interpreted as an array when submitted.
<select name="subcat[]">...</select>
With PHP it can be accessed (if POSTed) like this:
<?php
$subCatArr = $_POST['subcat'];
$firstIndex = $subCatArr[0];
$secondIndex = $subCatArr[1];
Oh yeah, and reusing IDs in HTML is not valid. They must be unique.
UPDATE After better understanding OP's intent:
If I understand the intent of this spaghetti code (that's a term of endearment, OP), the user may select one category and one subcategory, which is based on the category that he/she selected. Then the user submits the form and that selection is recorded in the database.
First of all, let's get rid of the use of table elements, because they're unnecessary. Secondly, you only need one select for the subcategory.
<form action='submitsite.php' method='POST'>
<label>category(optional)</label>
<select name='cat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "1">music </option>
<option value = "2">film </option>
</select>
<div id="subcatDiv" style="display:none;">
<select name='subcat' id='opts'></select>
</div>
.
.
.
<input type='submit' />
</form>
We can leave it blank, since it's not being displayed anyway.
Now, when the user makes a change, we'll either display the appropriate subcategories, or we'll just hide the div again:
<script type = "text/javascript">
function showForm(){
var selopt = document.getElementById("opts");
var seloptVal = selOpt.value;
var subcatDiv = document.getElementById("subcatDiv");
var options = "";
switch(seloptVal * 1) {
case 1:
options = "<option value='0'>Select</option>" +
"<option value='3'>pop</option>" +
"<option value='4'>rock</option>";
break;
case 2:
options = "<option value='0'>Select</option>" +
"<option value='5'>comedy</option>" +
"<option value='6'>drama</option>";
break;
default:
break;
}
if (options == "") {
subcatDiv.style.display = "none";
selopt.innerHTML = options;
} else {
selopt.innerHTML = options;
subcatDiv.style.display = "block";
}
}
</script>
Now you only have to deal with one select for the subcategory.
I have altered a lot of your code to make it valid html and also work as i "think" you want it as your question did not make it very clear.
Here is a list of amends I had to make:
Changed ID's to make it clear what they are for.
Removed duplicate ID's.
Closed off your table properly.
Completely changed your JavaScript to show and hide certain select's
Many more things that I have forgotten.
Please see this jsfiddle.
Fixed html:
<form action='submitsite.php' method='POST'>
<table>
<tr>
<td>category(optional)</td>
<td>
<select name="cat" id="selectType">
<option value="0">Select</option>
<option value="1">music</option>
<option value="2">film</option>
</select>
<div id="f1" style="display:none">
<select name='music' id="selectMusic">
<option value="0">Select</option>
<option value="3">pop</option>
<option value="4">rock</option>
</select>
</div>
<div id="f2" style="display:none">
<select name="type" id="selectFilm">
<option value="0">Select</option>
<option value="5">comedy</option>
<option value="6">drama</option>
</select>
</div>
</td>
</tr>
</table>
</form>
Fixed JavaScript:
$("#selectType").change(function() {
var selected = $(this).val();
$("#f1, #f2").hide();
switch (selected) {
case "1":
$("#f1").show();
break;
case "2":
$("#f2").show();
break;
}
});​​
document.forms[0].subcat will be an array.
document.forms[0].subcat[0] will be the first instance, etc.
p.s. IDs are supposed to be unique.
document.getElementById('f2').getElementsByTagName('select')[0]
You are violating HTML standards by reusing IDs, by the way.

populating different data with select onChange in php

i need some clarification on how to populate select(s) with data from mysql. Basically what I am trying to do is:
There will be a first select box with some data in it.
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
when the user selects a option in the first select,
there is a second select below that, which should reflect the values according to the selection made in the first select.
<select>
<option>1.1</option>
<option>1.2</option>
<option>1.3</option>
</select>
The data is commin from MySQL. I am not sure if need to post to same page, but if I do, how to retain the values alredy selected in the previous select boxes? do i need to use javascript?
any help?
Thanks.
You should use javascript so you don't need a page refresh. I just re-read your question and I'll have a solution involving an AJAX request in a second to pull dynamic data:
HTML
<select name="select1" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select2" id="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
jQuery
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
});
function getDropdownOptions() {
var val = $(this).val();
// fire a POST request to populate.php
$.post('populate.php', { value : val }, populateDropdown, 'html');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
populate.php
<?php
if (!empty($_POST['value'])) {
// query for options based on value
$sql = 'SELECT * FROM table WHERE value = ' . mysql_real_escape_string($_POST['value']);
// iterate over your results and create HTML output here
....
// return HTML option output
$html = '<option value="1">1</option>';
$html .= '<option value="b">B</option';
die($html);
}
die('error');
?>

Categories