Checkbox Take Value From Textbox - php

I have a problem to combine the checkbox and textbox values. Here my snipet code :
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
this is my php code to process that form:
$array_id_staf = $_POST['id_staf'];
$array_note= $_POST['note'];
for($a = 0; $a < count($array_id_staf); ++$a) {
echo $query1 = "UPDATE peserta SET note='$array_note[$a]' WHERE id= '$array_id_staf[$a]'<br>debugging";
//----------------------testing---------------------------#mysql_query($query1); // hold first for debugging
} // Closing for
if all checkbox were checked, the result os going fine. But if the second and 3rd were checked, array $array_note become wrong.
Please help me. Thanks in advance.

Related

Placing data in MySQL database from form fields created on the fly

I have a form that allows members to click a (+) sign, and it will put another form field there. They can do this to basically without limit.
The problem I have is if they do it, let's say, 3 times and fill out all 3, when I get the data to save it, it's placing the first field in the database and not the others.
Here is my code:
Here is the JavaScript that makes the div show as they push the (+) sign.
<script type="text/javascript">
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
document.getElementById('newlink').appendChild(div1);
}
</script>
<style>
.feed {padding: 5px 0}
</style>
This is part of the form that does the above...
<td width="50%" valign="top">
<div id="newlink">
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
<hr>
<p id="addnew">
+ Click Here To Add Another Biz/Traffic/Tools Site
</p>
<div id="newlinktpl" style="display:none">
<hr>
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
This is the part of the PHP code that would save it...
$i=0;
$linkname = $_POST["recname"][0];
while($linkname != ""){
$linkname = $_POST["recname"][$i];
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
$linkname = $res->real_escape_string($linkname);
$linkurl = $res->real_escape_string($linkurl);
$linktype = $res->real_escape_string($linktype);
$result299 = mysqli_query($res, "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')");
$i++;
}
It's all working except that is does not store all the data in the database (only the first one saves). That's the part I need help with please.
Please explain what I have done wrong and how to get it to store all the fields in the database, no matter how many the user creates and fills out.
I tested your code and it works fine so far if I use it like this:
$i=0;
$linkname = $_POST[recname][0];
while($linkname != ""){
$linkname = $_POST[recname][$i];
$linkurl = $_POST[reclink][$i];
$linktype = $_POST[rectype][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
There's no information about the $res object you're calling real_escape_string() on, so I'll just skip that for now. There are a couple of weaknesses in the code though:
You are referencing the post keys with barenames instead of strings.
PHP will gracefully assume you meant it as a string, but it will trigger a notice like Use of undefined constant recname - assumed 'recname'. Enclose them in quotes to make it clean.
Your use of the loop will result in an empty element inserted in the database every time.
You set the new linkname AFTER checking if $linkname is empty, but the variable contains the name of the last iteration. Instead, do something like this:
$i=0;
while($linkname = $_POST["recname"][$i]){
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
Your code only allows for one radio button to be checked at a time
You cannot use rectype[] as a name for radio buttons, as an equal name forms a group of radio buttons out of all the elements. You need to name them like this:
<input type="radio" name="rectype[0]" value="1"> Business Opp<br />
<input type="radio" name="rectype[0]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[0]" value="3"> Tools Site<br />
<input type="radio" name="rectype[1]" value="1"> Business Opp<br />
<input type="radio" name="rectype[1]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[1]" value="3"> Tools Site<br />
and so on. You can do that programatically in your javascript code like this:
<script type="text/javascript">
var counter = 1;
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
var inputs = div1.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
if (inputs[i].type == "radio") {
inputs[i].name="rectype[" + counter + "]";
}
}
counter++;
document.getElementById('newlink').appendChild(div1);
}
</script>
That said, I don't see why it should only save one item, unless you have a key constraint hitting or something else we cannot assume from the piece of code you shared.

Keep printing same form until submit button is clicked

Hi I'm quite new to php and I'm currently making a webpage similar to the ones used by supermarkets for stock management control as part of an assignment. I have the following form where the cashier would enter the product Id and the quantity of the item being purchased.
The form will then call another php file named cashsale.php which will take these inputs and update the tables in my database so that levels of stock on shelves in supermarkets are up to date with the new amounts (i.e. older qty - qty entered) and management can be advised when reorder is needed.
As it is the form works well, however I was advised to edit it in a way that a cashier can enter multiple products and quantities before submitting (i.e. the form will sort of show itself again) and allow the user to edit or remove any items before actually submitting the values to cashsale.php to manipulate the tables. I seem to be at a loss as to how this can be done.
I wanted to create a new button named "Add" which would display the form again, i.e. allow the user to check in more items, but I am confused as to how this can be done and also as to how I will be able to update tables then since I would be having more then just 2 inputs.
Can anyone help me on this please? Thanks in advance. The following is my html form:
center form action="cashsale.php" method ="post"
Product ID: <input name= "id" type="int" > <br>
Quantity:<input name="qty" type="int">
<input type="button" name = "Add" onclick="add">
<input type="Submit" name ="Submit" value = "Submit">
form center
I was not allowed to use html tags for form and center so I removed the < >. The following is some of the modifications done in the cashsale.php file just to give a clearer example.
$result = mysql_query("SELECT * FROM shelfingdetails where prodId =' " .$id. " '");
if (!$result){
die (mysql_error());
}
while ($row =mysql_fetch_array($result))
{
$qtyOnShelf= $row ['QtyOnShelf'];
$max=$row['max'];
$newQtyShelf=$qtyOnShelf-$qty;
}
$update=mysql_query("UPDATE shelfingdetails SET QtyOnShelf ='". $newQtyShelf. "' where prodId = '". $id. "';");
I hope someone can help. Thanks!
You just have to pass an array. For this you have to generate the inputs with PHP or javascript (I'm gona use jQuery to keep the code nice and simpe).
If you use PHP:
// PHP
<?php
if(isset($_POST['submit']) && $_POST['submit']){
//save data
} elseif(isset($_POST['Add']) && $_POST['Add']) {
$max = (int)$_POST['max']
} else { $max = 1; }
?>
<form action="" method="post">
<?php
for($i = 0;$i < $max;$i++){
?>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<?php
}
?>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="submit" name="Add" />
<input type="submit" name="Submit" value="Submit" />
</form>
If yo use Javascript:
//HTML
<form action="" method="post" id="form">
<div id="add">
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
</div>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="button" name="Add" onclick="addRow();" />
<input type="submit" name="Submit" value="Submit" />
</form>
// jQuery
function addRow(){
$("#add").append("<br />Product ID: <input name='id[]' type='int' >" +
"<br />Quantity: <input name='qty[]' type='int'>");
}
you have to use id[] and qty[] to pass them as an array and with the add button generate as many of them as you need. Like so:
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<input type="button" name = "Add" onclick="add">
Then on the backand use for loop to save all the data.
$max = count($_POST['id']);
$id = $_POST['id'];
$newQtyShelf = $_POST['qty'];
for($i = 0;$i < $max;$i++){
$update=mysql_query("UPDATE shelfingdetails
SET QtyOnShelf ='". (int)$newQtyShelf[i]. "'
WHERE prodId = '". (int)$id[i]. "';");
}
I just wanted to show you the idea, please don't use this specific code, because you should use mysqli instead of mysql and also mysqli_escape_string to make sure that the user not submits incorrect data.

Count checked checkboxes

I am new to HTML, I have a list of checkboxes on a form in an HTML page.
Each checkbox on each line represents a different category "I" "D" "C" and "S".
Part of my code is as follows:
<form>
1.<input type="checkbox" name="Personality_1.1" value="I"/>Animated &nbsp
<input type="checkbox" name="Personality_1.2" value="D" />Adventurous &nbsp
<input type="checkbox" name="Personality_1.3" value="C" />Analytical &nbsp
<input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />
2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful &nbsp
<input type="checkbox" name="Personality_2.2" value="D" />Persuasive &nbsp
<input type="checkbox" name="Personality_2.3" value="C" />Persistent &nbsp
<input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />
3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable &nbsp
<input type="checkbox" name="Personality_3.2" value="D" />Strong Willed &nbsp
<input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing &nbsp
<input type="checkbox" name="Personality_3.4" value="S" />Submissive<br /><br />
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then display the total of each category when the form is submitted.
Such a: "Five D's have been checked" "Three C's have been checked"
Is there a way I can do this with Javascript or PHP? If so can anyone help direct me to figure out how to do so?
Well, with PHP, assuming your submitting the form with POST:
$counts = array_count_values($_POST);
And you'll get an associative array with the values as keys and counts as values. So if for example 3 D's have been checked, $counts['D'] will hold "3".
As an example, you can use something like this:
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var allChk = document.getElementsByTagName("input"),
counts = {},
i, j, cur, val;
for (i = 0, j = allChk.length; i < j; i++) {
cur = allChk[i];
if (cur.type === "checkbox") {
if (!(cur.value in counts)) {
counts[cur.value] = 0;
}
if (cur.checked) {
counts[cur.value]++;
}
}
}
for (val in counts) {
console.log("There are " + counts[val] + " " + val + "'s checked");
}
};
};
DEMO: http://jsfiddle.net/Dwjez/1/
Click the button, after checking some checkboxes, and look at your console to see the results. It just finds all checkboxes, and stores the number of checked ones, per value, in an object literal...then the final loop is there just to print the results in the console.
This was just a simple example with event handling, but I'd suggest looking at addEventListener vs onclick to see another way to handle events (with addEventListener).
jquery-:
var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length;
javascript--:
var checkboxLength = document.forms["formName"].elements["checkbox[]"].length;
var checkboxes = document.forms["formName"].elements["checkbox[]"];
for(var i = 0; i < checkboxLength; ++i) {
if(checkboxes[i].checked) {
// do stuff
}
}
how about...
var getCount = function(type) {
return document.querySelectorAll('input[value='+type+']:checked').length;
}
alert(getCount('A') + "As have been selected");
and it looks like you would be better off using a radio group instead of checkboxes. From looking at your html, do you want the user to be able to select more than one item in each section?
Here is the code you want. Try it and let me know.
<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" action="next_page.php" method="post">
<input type="checkbox" name="chkGuar[]" value="mike"> Mike<br />
<input type="checkbox" name="chkGuar[]" value="joy"> Joy<br />
<input type="checkbox" name="chkGuar[]" value="harry"> harry<br />
<input type="checkbox" name="chkGuar[]" value="watson"> watson<br />
<input type="checkbox" name="chkGuar[]" value="george"> george<br />
<input type="checkbox" name="chkGuar[]" value="peter"> Peter<br />
<input type="submit" name="chksbmt" value="Send" />
<!-- <div id="myrow" style="visibility:hidden">
<input type = text name ='txtGRTNo' tabindex = 19 size="20">
</div>
<div width="338" align="left" colspan="3" height="12"></div> !-->
</FORM>
</BODY>
</HTML>
next_page.php
<?php
if(isset($_POST['chksbmt'])){
$counts = count($_POST['chkGuar']);
echo "this is the next page. you checked $counts checkbox <br /><br />";
for($i=1;$i<=$counts;$i++){
echo "<input type='text' style='border:1px solid #000;' value='your text box here' /><br/><br/>";
}
}
You should write your form code like this:
<form>
1.<input type="checkbox" name="chkI[]" value="I1"/>Animated
<input type="checkbox" name="chkD[]" value="D1" />Adventurous
<input type="checkbox" name="chkC[]" value="C1" />Analytical
<input type="checkbox" name="chkS[]" value="S1" />Adaptable
2.<input type="checkbox" name="chkI[]" value="I2"/>Playful
<input type="checkbox" name="chkD[]" value="D2" />Persuasive
<input type="checkbox" name="chkC[]" value="C2" />Persistent
<input type="checkbox" name="chkS[]" value="S2" />Peaceful
3.<input type="checkbox" name="chkI[]" value="I3"/>Sociable
<input type="checkbox" name="chkD[]" value="D3" />Strong Willed
<input type="checkbox" name="chkC[]" value="C3" />Self-sacraficing
<input type="checkbox" name="chkS[]" value="S3" />Submissive
</form>
Look at the "name" and "value" attributes. I made I change to the values of them.
You say:
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then
display the total of each category when the form is submitted.
If you make a submit...
<?php
if(!empty($_GET['chkD'])) {
$counterChkD = 0;
foreach ($_GET['chkD'] as $chkD){
echo $chkD."\n";
//echoes the value set in the HTML form for each checked checkbox associated with the "D" value
//so, if I were to check "Adventurous", "Persuasive", and "Strong Willed" it would echo value D1, value D2, value D3.
$counterChkD++;
}
echo "# of 'D-CheckBoxes' checked: ".$counterChkD."\n";
}
?>

Check all checkbox and store all selected items in a global variable

I have a list of emails with a checkbox next to it, the user will be able to select which address he/she wants to email. Now i've added another checkbox that when checked will check all the other checkbox. Below is the code i wrote (with help from stackoverflow of course) :
<SCRIPT LANGUAGE="JavaScript">
function selectFunction (checkall,field)
{
if(checkall.checked==true){
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}else{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
}
</script>
<form name="myform" action="profile-invite.html" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">aaa#xxx.com<br>
<input type="checkbox" name="list" value="2">bbb#xxx.com<br>
<input type="checkbox" name="list" value="3">ccc#xxx.com<br>
<input type="checkbox" name="list" value="4">ddd#xxx.com<br>
<input type="checkbox" name="list" value="5">eee#xxx.com<br>
<input type="checkbox" name="selectallcb" value="Check All"
onClick="selectFunction(document.myform.selectallcb,document.myform.list)">
<input type="submit" name="formSubmit" value="Submit" />
</form>
The "select all" function works fine, but using print_r i saw that when the submit button is clicked, the submited value is the last checkbox that i selected. For example if i click 5-3-1-2, the value in $_POST is "2" and not the rest.
i realized that my code can only register ONE selected checkbox, therefore only the last one is taken into account. So I rewrote the code by adding [] behind the name of the checkbox :
<form name="myform" action="profile-invite.html" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list[]" value="1">aaa#xxx.com<br>
<input type="checkbox" name="list[]" value="2">bbb#xxx.com<br>
<input type="checkbox" name="list[]" value="3">ccc#xxx.com<br>
<input type="checkbox" name="list[]" value="4">ddd#xxx.com<br>
<input type="checkbox" name="list[]" value="5">eee#xxx.com<br>
<input type="checkbox" name="selectallcb" value="Check All"
onClick="selectFunction(document.myform.selectallcb,document.myform.list)">
<input type="submit" name="formSubmit" value="Submit" />
</form>
Now, it registers the multiple selections when i checked with print_r.(if i click 5-3-1-2, the value in $_POST is now [0]=>5,[1]=>3,[2]=>1,[3]=>2.)
But the "select all" checkbox doesn't work anymore. I assume is due to the [] which transformed the field into an array. I tried various methods (by replacing "document.myform.list" with "document.myform.list[]" etc. ) None is working so far, i'll continue experimenting but if anybody have a clear idea on how to merge the 2 codes above please help.
Thank You
Change this:
onClick="selectFunction(document.myform.selectallcb,document.myform.list)"
to this:
onClick="selectFunction(document.myform.selectallcb,document.myform['list[]'])"
Here's the fiddle: http://jsfiddle.net/NxfH6/

Upload multiple form $_post arrays to database

I'm trying to upload a form to the database, that uses the same field names, as part of a CMS.
This is the form (I have used JQuery to multiply the div the number of options per product):
<form method="post" enctype="multipart/form-data" action="testing.php">
<div class="OptExtra1">
<h3>Additional Option</h3>
<label for="RESAddType">File type (i.e. “CD” or “Download”)</label>
<input name="RESAddType[]" type="text" id="RESAddType" size="48" class="FW" />
<label for="RESAddTitle">File title (i.e. “Boxed Set of 4 CDs”)</label>
<input name="RESAddTitle[]" type="text" id="RESAddTitle" size="48" class="FW" />
<label for="RESAddFType">File format (As “MP3” // “WORD” // “PDF”)</label>
<input name="RESAddFType[]" type="text" id="RESAddFType" size="48" class="FW" />
<label for="RESAddPrice">File price (Enter as “6.99” – <strong>NO “£” SIGN!</strong>)</label>
<input name="RESAddPrice[]" type="text" id="RESAddPrice" size="48" class="FW" />
<label for="RESAddFName">File name</label>
<input name="RESAddFName[]" type="text" id="RESAddFName" size="48" class="FW" />
<label for="RESAddTxt">File text</label>
<textarea name="RESAddTxt[]" id="RESAddTxt" cols="70" rows="50" class="mceAdvanced"></textarea>
<label for="RESAddSample">File text</label>
<textarea name="RESAddSample[]" id="RESAddSample" cols="70" rows="50" class="mceVSimple"></textarea>
<input type="button" value="Add another option" class="SubmitButton" onclick="inserter()" />
<hr />
</div>
<p><input type="submit" name="submit" value="Add Resource" class="SubmitButton"/><input type="hidden" name="RESCatCode" value="2" /><input type="hidden" name="RESCatSubCode" value="5" /><input type="hidden" name="submitted" value="true" /></p>
and this is what I have so far for the PHP
if(isset($_POST['submitted'])){
$RESCode = 100;
$RESAddType = $_POST['RESAddType'];
$RESAddTitle = htmlentities($_POST['RESAddTitle'], ENT_QUOTES);
$RESAddFType = $_POST['RESAddFType'];
$RESAddPrice = $_POST['RESAddPrice'];
$RESAddFName = $_POST['RESAddFName'];
$RESAddTxt = mysql_real_escape_string($_POST['RESAddTxt']);
$RESAddSample = mysql_real_escape_string($_POST['RESAddSample']);
for ($i=0; $i < count($_POST['RESAddType']); $i++) {
$OptionQuery = mysql_query ("INSERT INTO ResAdd (RESAddCode, RESCode, RESAddType, RESAddTitle, RESAddFType, RESAddPrice, RESAddFName, RESAddTxt, RESAddSample) VALUES ('', '".$RESCode."', '".$RESAddType."', '".$RESAddTitle."', '".$RESAddFType."', '".$RESAddPrice."', '".$RESAddFName."', '".$RESAddTxt."', '".$RESAddSample."');");
}
header("Location: welcome.php");
exit;
}
It kind of worked, but is just putting in the word "array" into the database. Also the htmlentities and mysql_real_escape_string posts don't upload anything to the database.
Any ideas please?
You've forgotten something :)
$OptionQuery = mysql_query ("INSERT INTO ResAdd (RESAddCode, RESCode, RESAddType, RESAddTitle, RESAddFType, RESAddPrice, RESAddFName, RESAddTxt, RESAddSample) VALUES ('', '".$RESCode[$i]."', '".$RESAddType[$i]."', '".$RESAddTitle[$i]."', '".$RESAddFType[$i]."', '".$RESAddPrice[$i]."', '".$RESAddFName[$i]."', '".$RESAddTxt[$i]."', '".$RESAddSample[$i]."');");
Look at all these $i in the code above. If you don't use them, the script will try to use the entire array (and trying to print or save an array as a string always results in printing "Array").
P.S.I've edited my answer. Sorry for the previous one, I've misunderstood the code and posted a wrong answer.
You need to looping
$cnt=count($_POST['RESAddType']);
for ($counter=0; $counter < $cnt; $counter++)
{
$_POST['RESAddType'][$counter]// to access the value
$_POST['RESAddPrice'][$counter]//
//create your query here
}

Categories