Good day!
Im currently having problems with inserting values with checkbox and hidden field. Any tips or solutions are greatly appreciated.
So my problem is this: I have a form with only checkboxes in it and a submit button and If I check one of the values in a checkbox a hidden upload field will be displayed the hidden value must be connected to the chosen value in the checkbox. How can I insert the hidden value to the corresponding checkbox value in a database. For example
HTML:
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue">
Value 1
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue">
Value 2
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
PHP:(Updated) This is what I have now. when I dont check the 1st checkbox. the hidden_one in the 2nd checkbox isnt inserting
foreach($_POST['value'] as $key=>$value ){
$hidden_one = $_POST["hidden_one"][$key];
$sql = "INSERT INTO sample (value, hidden_one) VALUES ('$value','$hidden_one')";
$result = mysqli_query($connection, $sql);
}
If I check value 1 and entered a sample1 in the hidden form and I check value 2 and entered a sample2 in the hidden form. sample 1 must be in the same column as value 1 and sample 2 must be in the same column as value 2. its not inserting properly
UPDATE:
So I changed the code into this
foreach($_POST['value'] as $key=>$value ){
$hidden_one = $_POST["hidden_one"][$key];
but the problem is sometimes its not inserting correctly. Sometimes hidden_one is empty in the database. I'm really lost at the moment. Can't find a solution elsewhere.
This is my updated form
Im seeing a pattern, when I skipped a checkbox like I check value1 then skip value2 then check value3. value3 hidden isn't inserted. Still not solved :( lol this is driving me crazy. at the verge of quitting. lol
One way you could insert the value of your checkbox into your hidden input fields, is by making a click function that takes $(this).val(), which is your clicked elements value. You can then put that value into a variable. You then go to target the parent element/container for the targeted checkbox and find the corresponding input field. You then simply set the value of that input field with the declared value of the checkbox.
Note that the notation for this JavaScript is in jQuery, and you will need to include a jQuery library in order for this solution to work.
$(document).ready(function () {
$('[name="value[]"]').click(function(){
var mySelect=$(this).val();
if( $(this).prop('checked') ) {
$(this).parent().find('input[name="hidden_one[]"]').val(mySelect);
}
else {
$(this).parent().find('input[name="hidden_one[]"]').val("");
}
})
});
Example:
$(document).ready(function () {
$('[name="value[]"]').click(function(){
var mySelect=$(this).val();
if( $(this).prop('checked') ) {
$(this).parent().find('input[name="hidden_one[]"]').val(mySelect);
}
else {
$(this).parent().find('input[name="hidden_one[]"]').val("");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue 1">
Value 1
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue 2">
Value 2
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
Direct JS Fiddle link
When it comes to inserting the value(s) into the database, it's hard for me to give a concise answer, because I don't have any debugging information on your application, so I don't know if you have structered it properly. I would assume you have either an AJAX function or a form action to post your values. As you noted in your own attempt, is that the values come up as an array that you will have to loop through. However, I am uncertain of the nested foreach loops.
Let me know if you need any further assistance, and in that case, update your question with potential error messages, corresponding form/ajax code, and if your PHP file holds any other relevant information, add that too.
A rough example could be:
<?php
$hidden_one_array=array_values($_POST['hidden_one']); //our posted array
$i=0; // iterator
$length=count($hidden_one_array); //length of the array
while($i < $length) {
$sql="INSERT INTO sample (value, hidden_one) VALUES ('$value','$hidden_one_array[$i]')";
$result=mysqli_query($connection, $sql);
$i++;
}
?>
What we're doing here is basically looping through the array, using the iterator value as our index pointer to each respective array index to insert into the database.
Also note that you should probably look into prepared statements to prevent sql injection. You are already using mysqli_ so might as well take advantage of it.
Related
I'm not sure how to ask this question. It procedural question I believe.
<input type="hidden" name="1[]" value="dummy">
<input type="radio" name="1[]" value="5">
<label> Very Good </label>
<input type="radio" name="1[]" value="4">
<label> Good </label>
<input type="text" name="1[]" size="20">
<br>
<input type="hidden" name="2[]" value="dummy">
<input type="radio" name="2[]" value="5">
<label> Very Good </label>
<input type="radio" name="2[]" value="4">
<label> Good </label>
<input type="text" name="2[]" size="20">
$_POST output:
[1] => Array
(
[0] => Text misc
)
[2] => Array
(
[0] => 5
[1] =>
)
From this I construct and INSERT statement.
INSERT INTO coached_tracked (coached_id, value, note)
VALUES ($key, $value[0], $value[1]);
This is are dynamically generated form inputs. A radio button, text field pair.
How can I handle an occurrence where the radio is not selected and the text field has value, like in the first instance. I want the option of having nothing selected so a default value seems not called for. I tried with both with and without a dummy value (I saw an example suggesting a hidden field as a possible solution.)
Suggestions.
You should not tell the database what ID to use. Let the database itself determine that by using an auto-incremented column.
First, start with a logical input name. Using just numbers is extremely confusing and looking at your code, I have absolutely no idea what you're doing. We also want everything to go into the same PHP $_POST variable to not have to iterate over all possible number cominations. That means we can just iterate over the one single array.
Let's say you're adding a coach to a database, so logically we would start with:
<input name="coach">
Now when we want to add multiple coaches instead of just one, we can use HTML array names, however I would recommend you hard-code them instead of auto-incrementing in your HTML, which should simplify things later on. We also pluralize it to coaches:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>]">
<?php
}
Now if each coach contains a certain properties, let's say name, salary, note, etc, we can add the properties to the input names like so:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>][name]">
<input name="coaches[<?=$i?>][salary]">
<input name="coaches[<?=$i?>][note]">
<?php
}
Then in PHP you just iterate over $_POST['coaches'] and then use the properties for each coach how you wish:
if (isset($_POST['coaches'])) {
foreach ($_POST['coaches'] as $coach) {
$name = $coach['name'];
$salary = $coach['salary'];
$note = $coach['note'];
// Now execute the query:
// INSERT INTO coached_tracked (name, salary, note)
// VALUES ($name, $salary, $note);
}
}
Note: remember to sanitize any user-supplied data by using prepared statements with bound parameters to make sure you're not open to SQL injection attacks.
I'm doing this one using PHP.
I'm doing some basic quiz application and it has a backend. On my backend, I am setting up a quiz for students to answer. One of my interface is like this.
If the user checked the box, it means 1950 is the answer. How would I process that one in my database to determine that 1950 has been the answer of the question.
My Database is like this.
tbl_choices
Id,Choice,isAnswer
so ideally, it would be stored like this.
tbl_choices
ID CHOICE isAnswer
001 1900 0
002 1800 0
003 1950 1
004 1850 0
My question here is how would I code it in a sense when a user will check the checkbox and the textinput right beside it will have a value of isAnswer as 1.
Just an additional info: When a user will click that + button it will add a new textinput and if user will click - button it will delete a textinput, but I got that all covered.
The choices are dynamic, it will changed, that above that I've shown you is just an example.
P.S: Sorry for the title, I don't know what's the title of this kind of question :-)
Your help would be greatly appreciated and rewarded!
you can try html like this :
<input type="checkbox" value="1900" name="answer1[]">
<input type="text" value="1900" name="answer2[]" />
<input type="checkbox" value="1800" name="answer1[]">
<input type="text" value="1800" name="answer2[]" />
<input type="checkbox" value="1950" name="answer1[]">
<input type="text" value="1950" name="answer2[]" />
<input type="checkbox" value="1850" name="answer1[]">
<input type="text" value="1850" name="answer2[]" />
and then use php code:
foreach($_POST['answer2'] as $v){
if(in_array($v, $_POST['answer1'])) {
$s = 1;
}else
$s = 0;
$sql = "INSERT INTO table VALUES(null, $v, $s)";
}
also on click plus update values of both check box and text field
in general you can use checkboxes as an array when submiting information, just name the checkboxes as an array like
<input type="checkbox" value="1900" name="answer1[]">
<input type="checkbox" value="1800" name="answer1[]">
<input type="checkbox" value="1950" name="answer1[]">
<input type="checkbox" value="1850" name="answer1[]">
then on the server side you handle $_POST["answer1"] as an array and cycle through the possible answers, something like this
if (is_array($_POST["answer1"]))
{
foreach($_POST["answer1"] as $answer)
{
// insert into database here
}
}
important: this will only show what a user actualy selected, if an option is not clicked then it will not be part of the array
I think it would make sense to have more than one table, one for the questions with their options and then one for the answers with the fields id, choice_id. Otherwise it is going to make generating the questions a lot more difficult especially when a number of students answer the same question?
One more thing, you could add up in the answers of your question, add row and delete row based on + and - button.
The code for that:
<script type="text/javascript">
$(document).ready(function() {
$("#plus").click(function() {
$('#mytable2 tbody>tr:last').clone(true).
insertAfter('#mytable2 tbody>tr:last');
$('#mytable2 tbody>tr:last #st').val('');
$('#mytable2 tbody>tr:last #newst').val('');
$('#mytable2 tbody>tr:last #plus').val('+');
return false;
});
});
for more detail, you may refer following link:
Add Row on Button click
I have a variable number of fields in a form.
The number of text fields are defined by the user with a function in jquery, but the final code of the form (example) is this:
<form id='form_educ' name='form_educ' method='post' action='form/educ.php'>
<div id='educ'>
<input type='text' name='date1' id='date1'/>
<input type='text' name='date2' id='date2'/>
<input type='text' name='date3' id='date3'/>
<input type='text' name='date4' id='date4'/>
....
</div>
<input type='submit' name='form_educ' value='Refresh'/>
</form>
These text fields when added by the user is create a sql INSERT TO (in another file):
$date = clean($_GET['date']);
"INSERT INTO educ (index_of_form, date, email) VALUES('$index', '', '" .mysql_real_escape_string($_SESSION['SESS_EMAIL']). "')";
$date is date1, or date2, or date3 or date4 (example).
Now in the file educ.php I want to update all text fields in the mysql database.
Usually it is a
$example = clean($ _POST ['example']);
I can do an update in the table and is resolved.
But in my case how can I get all the values โโof the text field on the form and set the $_POST var if the number of fields is variable (could be date1, date2, date3, date4)?
I can think of no reason why form field name should be a unknown variable. Unless you're dealing with repeatable fields, in which case you would use an array like dates[], and you'd know what to expect in the process script.
For additional info see for example: http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/
Word of warning for future. When you make the field repeatable, allow users also to delete the fields they might have accidentally insertet. Watch out in the process script missing array keys (numerical index from 0โ10 might be missing some values if the user deleted some form fields before submitting). You can reset the array keys with the array_merge function. Missing keys is an issue if you have two arrays you are trying to add into database as syncronized.
Updated to answer the comment.
Sorry, I don't undestand your question. You don't necessarily have to use hidden field. What you need is a database structure to match your forms function: to support one to many relationship. After all you are inserting multiple dates that relate to one person, or some specific event type, or what ever. Lets assume one user wants to add his three favorite dates in the world. Your form's source code looks like:
<input type="text" name='dateLover' id='dateLover'/>
<input type="text" name="dates[]" id="date1" /> //you need a increasing variable for these id numbers (or dont't put the id at all)
<input type="text" name="dates[]" id="date2" />
<input type="text" name="dates[]" id="date3" />
In addition you could have more fields such as <input type="text" name="extra" />. In submitted $_POST array there would be variables and arrays like: $_POST['dateLover'], $_POST['date'][0], $_POST['date'][1], $_POST['date'][2], $_POST['extra']. You'd take the non-repeatable values straight out of the $_POST array but you need a foreach (or some else loop) to handle the dates array.
Your database has to contain two tables (structure simplified):
person: id, dateLover
date: id, dateLover FK to person.dateLover, date
In your process script you have to:
insert a new dateLover to person and use last_insert_id to get his id
use a foreach to insert new dates to table date (with a dateLover's id as FK)
This all is pretty well demonstrated in the link I supplied earlier. For now, it's hard to give an complete example without undestanding the actual problem.
Update 2.
You are serializing the form, not the div's. So your (dynamically generated) could look like this:
<form id="form_educ" name="form_educ" method="post" action="form/educ.php">
<div id="educ">
<div><!--This is for layout only-->
<input type="text" name="dates[]" id="date0" />
<input type="text" name="names[]" id="name0" />
</div>
<div>
<input type="text" name="dates[]" id="date1" />
<input type="text" name="names[]" id="name1" />
</div>
<div>
<input type="text" name="dates[]" id="date2" />
<input type="text" name="names[]" id="name2" />
</div>
</div>
<input type="submit" name="form_educ" value="Refresh" />
</form>โ
And in your process file you take these arrays from $_POST array and insert them into database maybe like this (with properly escaped and checked values of course...):
//dynamic part of the query
$qEnd = '';
$i = -1;
//this is static part of the query
$qBeginning = "INSERT INTO `date` (`id`, `date`, `name`) VALUES ";
foreach ($_POST['dates'] as $key => $date){
$i++;
$qValues[$i] = "(null, '{$date}', '{$_POST[names][$i]}')"; //never do this, always check values...
//value sets are concatenated one after another to the $qEnd
$qEnd .= $qValues . ',';
}
//combine the query parts and remove extra "," from the end
$q = $qBeginning . rtrim($qEnd, ',');
//now the (single) query ($q) is ready to be executed, echo it just for the fun of it
id should be auto increment field, or this kind of stuff doesn't work on the fly.
Again, this all should be clear in the jQuery link example so please read it carefully.
You should know all of the possible columns that could be updated before hand. Just check to see if those are set in the $_POST variable, then if they are append the insert or update statement with those values.
DANGER: Just looping on the $_POST variable looking at all params may end up inserting not database related POST fields into your insert statement and breaking.
Also when using these methods, be aware of SQL Injection, and use parameterized queries and never directly insert POST variable names or values into the SQL Statment.
I am doing this :
function GETVALUE()
{
if(document.getElementById("requirenewpage").checked == true)
{
document.getElementById("requirenewpage").value;
var cval= parseInt(document.getElementById("requirenewpage").value);
}
}
HTML-----------------------------
<input type="checkbox" id="requirenewpage" unchecked value= "GETVALUE();" >
I need to insert into a mysql table , 0 or 1, which is taken from the VALUE attribute of the checkbox.....but am not able to do it...please help???
Its always inserting 0 into the database, albeit am setting the value as 1 in the function GETVALUE().....
Actually you don't need any of this i think. You can use this html:
<input type="checkbox" id="requirenewpage" value= "1" >
and the checkbox will send a value of 1 to the server if checked, otherwise it won't send anything (and the corresponding $_POST['requirenewpage'] or $_GET['requirenewpage'] won't be set).
If the checkbox is checked it's value is sent to the server and a key in the $_POST array (if you use POST) is created with the name of the checkbox and the value of hte checkbox.
you can do, serverside:
$chkboxval = 0;
if (isset($_POST['requirenewpage'])){
$chkboxval = $_POST['requirenewpage'];
}
I'm shocked that nobody has answered this correctly yet...
Change the checkbox to the following:
<input type="checkbox" id="requirenewpage" name="requirenewpage" value= "1" />
The ID of an input element is used for script access and styling only, if you want to submit the element in a form it must have a name attached to it.
You are wrong with your html. Change your checkbox code from
<input type="checkbox" id="requirenewpage" "unchecked" value= "GETVALUE();" >
to
<input type="checkbox" id="requirenewpage" onclick= "GETVALUE();" >
i have an html form full of text fields, checkbox's , and radio fields.
i wanted to get all the names of the fields so that i can get started in validating the information in them.
the method i am using to get them is
if(isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
print $name."<br/>";
}
}
but i noticed that it only displays textbox and textarea field names and it doesnt include checkbox and radio field names through this submission. do i need to include anything for it to grab the field names of those?
Checkboxes and radio buttons work a little differently than your standard inputs. If a checkbox is present on a form that doesn't necessarily mean that it will be available in the resulting POST information. Rather, those values will only be avialable if they are actually marked (checkboxes checked and radio buttons selected). The proper way to test for their value in PHP is not to check the field value but rather to check isset() first.
For a checkbox:
$data['my_checkbox'] = isset($_POST['my_checkbox']) ? 'on' : 'off';
and for a radio button:
$data['my_radio'] = isset($_POST['my_radio']) ? $_POST['my_radio'] : false;
To be a little more descriptive let's say you have the following form:
<form action="test.php" method="post">
<input type="text" name="email" value="" />
<input type="checkbox" name="active" value="Yes" />
<input type="submit" value="Submit" />
</form>
If I were to submit that form with an email value of 'test#email.com' but not check the checkbox I would have the following in $_POST:
Array (
'email' => 'test#email.com'
)
However, if I were to submit the same form with the same email address and check the checkbox I would have the following:
Array (
'email' => 'test#email.com',
'active' => 'Yes'
)
Hope that helps.
0./ Try using the following code to see the raw posted data:
echo '<pre>';
print_r($_POST);
echo '</pre>';
1./ Make sure you use a name attribute value for your checkbox and radio inputs.
Typically for checkboxes, it will be an array.
<input type="checkbox" id"=fruit-apple" name="fruits[]" value="apple" />
<input type="checkbox" id="fruit-pear" name="fruits[]" value="pears" />
2./ Make sure they sit inside the form tag.
3./ If you submit using a javascript call, try disabling javascript and see if the error stays. If it does not, you know your javascript is the culprit.