Insert all HTML form fields (filled and empty) to array php - php

I have a large HTML form where I currently insert filled html fields into and array. When I print out my $_POST['rep_list']; it gives me the keys and values filled out from the form. But what I need is an array with all form fields (even the ones not filled out). Any suggestion/examples on how to achieve this?
<form action="insert-data.php" name="workCard" method="POST">
<fieldset>
<legend><h3>Repair</h3></legend>
<table>
<tr>
<th>Description</th>
<th>Front</th>
<th>Back</th>
</tr>
<tr>
<td>tire</td>
<td><input type="checkbox" name="rep_list[tire_front]" value="tire_front" /></td>
<td><input type="checkbox" name="rep_list[tire_back]" value="tire_back" /></td>
<td>alm <input type="checkbox" name="rep_list[tire_reg]" value="tire_reg" /></td>
<td>indl <input type="checkbox" name="rep_list[tire_indl]" value="tire_indl" /></td>
</tr>
<tr>
<td>Tube</td>
<td><input type="checkbox" name="rep_list[tube_front]" value="tube_front" /></td>
<td><input type="checkbox" name="rep_list[tube_back]" value="tube_back" /></td>
</tr>
<tr>
<td>Hub.rep.</td>
<td><input type="checkbox" name="rep_list[hub_front]" value="hub_front" /></td>
<td><input type="checkbox" name="rep_list[hub_back]" value="hub_back" /></td>
<td>just. <input type="checkbox" name="rep_list[hub_adjust]" value="hub_adjust" /></td>
etc…....

If you want to do this without javascript you can create text input's for all checkboxes. For example:
<td>
<input type="hidden" name="rep_list[tire_front]" value="False" />
<input type="checkbox" name="rep_list[tire_front]" value="True" />
</td>
When you check the POST in PHP you can determine if a checkbox is checked or not by checking the value .When the POST value is True the checkbox was checked and False is unchecked.

With checkboxes if they are ticked they will be set in the HTTP post with their given value (or default of 'on' if a value is not set). If they are not ticked no value will be sent.
To check if a checkbox was ticked in PHP you could simply check if a POST value was set:
$tire_front = isset($_POST['rep_list']['tire_front']);
If you wanted to do this for every item you could create an array of the keys and loop through each of these:
$fields = array(
'tire_front',
'tire_back',
'tire_reg',
'tire_indl',
'tube_front',
'tube_back',
'hub_front',
'hub_back',
'hub_adjust'
);
foreach ($fields as $field) {
$rep_list[$field] = isset($_POST['rep_list'][$field]);
}
$rep_list would then contain an entry for each of the fields with a value of true if ticked, or false if not.

Related

Need to get the Checked input and checkbox value using jquery in php

Am having table data (retrieve data from mysql table and fetch in to table). table contains several records.I want to display checked checkbox value with input box value and checkbox when i clicking button in php. Checked checkbox value and checked input has deen displayed correctly using join function. but checked with checkbox is not showing correctly. In my code, when i clicking button all checked check values are displayed. my problem to display only checked checkbox with checkbax using join function.
My table:
<table border="0" cellpadding="10" cellspacing="1" width="500" class="tblListForm">
<tr class="listheader">
<td></td>
<td>Username</td>
<td>First Name</td>
<td>Last Name</td>
<td>Permissions</td>
<td>CRUD Actions</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
if($i%2==0)
$classname="evenRow";
else
$classname="oddRow";
?>
<tr class="<?php if(isset($classname)) echo $classname;?>">
<td><input type="checkbox" class="chk_id" name="chk_id" id="chk_id" value="<?php echo $row["userId"]; ?>" /></td>
<td><?php echo $row["userName"]; ?></td>
<td><input type="text" name="firstName" class="firstName" id="firstName" value="<?php echo $row["firstName"];?>" /></td>
<td><?php echo $row["lastName"]; ?></td>
<td><input type="checkbox" name="grant" class="grant" id="grant" value="Y" /></td>
<td><img alt='Edit' title='Edit' src='images/edit.png' width='15px' height='15px' hspace='10' /> <img alt='Delete' title='Delete' src='images/delete.png' width='15px' height='15px'hspace='10' /></td>
</tr>
<?php
$i++;
}
?>
</table>
<input type="button" id="save_value" name="save_value" value="Save" />
my jquery code what i have tried:
$('#save_value').click(function () {
alert("Checkbox running");
var chk_id = [];
var firstName = [];
var grant = [];
$.each($("input[ id='chk_id']:checked"), function () {
chk_id.push($(this).val());
firstName.push($(this).parent().parent().find("#firstName").val());
grant.push($(this).parent().parent().find($("#grant").is(':checked'));
});
alert(chk_id);
alert(firstName);
alert(grant);
});
Here,
am getting checked checkbox and checked input value. my problem to dispaly the checked checkbox with check value.
Thanks#
You made a few small mistakes:
You can't have multiple elements with the same ID, IDs must be unique. So I removed all duplicate IDs from your HTML (id="chk_id",id="firstName",id="grant") and in your JS, used the classes instead.
You missed a closing bracket in grant.push($(this).parent().parent().find($(".grant").is(':checked')));.
.find($(".grant").is(':checked')) isn't working as you expect, and also not necessary.
Use this instead: .find(".grant:checked").
And finally, the reason why your alert showed two values whether the checkboxes were checked or not: grant.push( ... ); always pushes something into the array, if the jQuery-selector matched nothing and would return false, that value would still be pushed into the array.
In fact, if you correct all three points above, and don't check the permission checkbox, the value in the array will be undefined. If you do check the box, it will be Y.
So, in order to make it work, you just have to put the grant.push( ... ); inside an if-clause, where you check for ".grant:checked":
if ($p.find(".grant:checked").length) {grant.push($p.find(".grant:checked").val());}
- $p stands for $(this).parent().parent(), I stored a reference in a var.
- .length checks if the length of the returned object is greater than 0. Without it, the if-clause would still always be true, because jQuery still returns an object (with value undefined).
See code snippet below for a demo:
$('#save_value').click(function() {
var chk_id=[], firstName=[], grant=[];
$.each($("input[class='chk_id']:checked"),function() {
var $row = $(this).parent().parent();
chk_id.push($(this).val());
firstName.push($row.find(".firstName").val());
if ($row.find(".grant:checked").length) {grant.push($row.find(".grant:checked").val());}
});
console.log(chk_id, firstName, grant);
});
table,input[type=button] {float:left;} /*ONLY SO console.log() DOESN'T COVER BUTTON*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0" cellpadding="0" cellspacing="0" width="500" class="tblListForm">
<tr class="listheader"><td></td><td>Username</td><td>First Name</td><td>Last Name</td><td>Permissions</td></tr>
<tr class="evenRow">
<td><input type="checkbox" class="chk_id" name="chk_id" value="4" /></td>
<td>sardhar</td>
<td><input type="text" name="firstName" class="firstName" value="sardhar" /></td>
<td>mohamed</td>
<td><input type="checkbox" name="grant" class="grant" value="Y" /></td>
</tr>
<tr class="oddRow">
<td><input type="checkbox" class="chk_id" name="chk_id" value="3" /></td>
<td>fg</td>
<td><input type="text" name="firstName" class="firstName" value="vb" /></td>
<td>vb</td>
<td><input type="checkbox" name="grant" class="grant" value="Y" /></td>
</tr>
</table>
<input type="button" id="save_value" name="save_value" value="Save" />
jsfiddle: https://jsfiddle.net/3utno9at/

PHP POST value from a looped table

Please help me out of this.....
I am designing a table which is inside a form.
the table is generated based on while loop.
In each row there is a download button.
when i click download the POST value should get the same row information.
But my POST variable is giving me the last row information only.
I tried using input-type as hidden... But it did not work
Here is the code for your reference
enter code here
<form name="simpleform" method="post" action="insert.php">
<?php
$data = "environment";
$user_name = $_SESSION['username'];
$serch = mysql_query("SELECT * FROM data WHERE (data_category = '" . $data . "') ");
while ($record=mysql_fetch_assoc($serch))
{?>
<tr class="warning">
<td >
<input type="text" value=<?php echo $record['data_ID'];?> readonly="readonly" >
<input type="hidden" value=<?php echo $record['data_ID'];?> name="dataid" />
</td>
<td >
<input type="text" value=<?php echo $record['data_name'];?> readonly="readonly" >
<input type="hidden" value=<?php echo $record['data_name'];?> name="dataname" />
</td>
<td >
<input type="text" value=<?php echo $record['data_downloads'];?> readonly="readonly">
<input type="hidden" value=<?php echo $record['data_downloads'];?> name="datadown" />
</td>
<td >
<input type="text" value="" >
<input type="hidden" value="" name="datause" />
</td>
<td>
<input type="submit" name="simplesubmit" value="Go to download" />
</td>
</tr>
<?php }
exit;
?>
</tbody>
</form>
The problem is that you are using the same name attribute for all your controls. Thus, when PHP receives the form, they get overwritten, and you only see the last value of the form.
The simplest way to avoid that is just appending [] to the end of your names -- eg name=dataid[]. This will make PHP take all arguments as an array, so you don't lose data.
The second problem, is that your submit button also has the same name - you should diversify it by using some row-specific data in its name, such as 'name="submit-'.$record['data_name'].'"'
For more info, more code from you is needed, such as what are the data you are printing like.
Every post button can have its name and value, so if you change your code to produce a traceable post button name you can just do whatever you want with that.
<table>
<tr>
<td>...</td>
<td>...</td>
<td><input type="submit" name="submit[1]" value="OK" />
</tr>
<tr>
<td>...</td>
<td>...</td>
<td><input type="submit" name="submit[2]" value="OK" />
</tr>
</table>
When the form is posted its very easy to capture which button is clicked;
if ($_POST["submit"]) {
$id = key($_POST["submit"]);
}
Thanks for info... and good response. As you said , i replaced the same and saw the post value is giving me all arguments as array. My purpose is to let the client download file that he clicks. so if the client click the first row button in the table, the post value should get only that Data_name. So that i can run a query to get the URL of that data_name and download

Retrieving form data into a php processor

I am having a problem understanding how to make the foreach function work. I have a form, that uses check boxes. I tried loading them as an array of check boxes, but I couldn't get the foreach function to work for me. I don't properly understand all of this. Let me post my form data real quick:
<form method="post" action="interests.php" name="interests">
<table width="500" cellspacing="3" cellpadding="3" bgcolor="#FF80FF" bordercolor="#800000">
<tr>
<td><input type="checkbox" name="check1" value="1"></td>
<td><input type="checkbox" name="check2" value="2"></td>
<td><input type="checkbox" name="check3" value="3"></td>
<td><input type="checkbox" name="check4" value="4"></td>
</tr>
<tr>
<td><input type="checkbox" name="check5" value="5"></td>
<td><input type="checkbox" name="check6" value="6"></td>
<td><input type="checkbox" name="check7" value="7"></td>
<td><input type="checkbox" name="check8" value="8"></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
<td colspan="2"><input type="reset"></td>
</tr>
</table>
</form>
Here is my php processor so far..:
<?php
for(x=1;x>8;x++){
$loop=
echo 'Your interests have been updated into the database, and those files will now</br>';
echo 'begin showing up in the files area on your files sections.';
?>
I know, not much, because I am stuck. I am banging my head. I need to parse this out, and check for values filled, so I can input the data into a database. Seems simple enough, but for some reason I cant get it!
After your edit , i suggest to give all your checkbox name='check[]' and in your php code you will get all values of inputs that are checked in $_POST['check'] without trying to do it manually,this code will echo all checked values :
<?php
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
echo $check.'<br/>'; //echo checked value
}
}
?>
First answer :
To minimize your HTML code using php use modulus ($a % $b Modulus Remainder of $a divided by $b) to show <tr> element before every 4 inputs
Try this :
<form method="post" action="interests.php" name="interests">
<table width="500" cellspacing="3" cellpadding="3" bgcolor="#FF80FF" bordercolor="#800000">
<?php
for($i=1;$i<=8;$i++){
if (($i-1)%4==0) echo "<tr>";
echo "<td><input type='checkbox' name='check$i' value='$i'/></td>";
}
?>
<tr>
<td colspan="2"><input type="submit"></td>
<td colspan="2"><input type="reset"></td>
</tr>
</table>
</form>

How can I get value of a text box which is looped using post method to insert value in database?

I had following code.My textbox attend is looped for number of times.I want to get value of each attend when my form is post to insert value in database.
<form method="post" action="insert.php">
<label>Subject</label>
<input type="text" maxlength="30" name="subject" />
<label>Total Lectures</label>
<input type="text" maxlength="30" name="total" />
<table width="537" border="1">
<tr>
<td width="90">Name</td>
<td width="139">Roll Number </td>
<td width="136"> </td>
<td width="144">Attendence</td>
</tr>
<?php
$query=mysql_query("SELECT * FROM STUDENT");
$i=0;
while($rec=mysql_fetch_array($query)){
$i++;
?>
<tr>
<td><?php echo $rec['name']; ?></td>
<td><?php echo $rec['roll_number']; ?></td>
<td> </td>
<td><input type="text" maxlength="10" name="atten" /></td>
</tr>
<?php } ?>
</table>
<input type="submit" value="submit" />
</form>
and my insert.php page is
if($_SERVER['REQUEST_METHOD']=='POST'){
$query=mysql_query("SELECT * FROM STUDENT");
while($rec=mysql_fetch_array($query)){
$attend=$_POST['atten'];
$subject=$_POST['subject'];
$total=$_POST['total'];
$query1=mysql_query("INSERT INTO course VALUES('$i','$subject','$total','$attend','')") or die(mysql_error());
}
}
I am getting only 1 value of text box.
The problem is that you have many inputs all with the name atten. When you post this form, only one of those values will be carried forward.
If you change the name to atten[] all of the values would be posted as an array, which you would then have to loop through to build you insert query.
You could access this posted array as follows:
$attendee_array = $_POST['atten'];
foreach($attendee_array as $attendee) {
// perform insert or build insert query (prefereable as you can do all these inserts at once) here
// make sure to escape your data for input
}
Change the names of your inputs:
<input name="subject[]" value="Lorem" />
<input name="total[]" value="ipsum" />
<input name="atten[]" value="dolor" />
Then:
$_POST['subject'][0] == 'Lorem'
$_POST['total'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an
indefinite amount of information through a form and get it processed
by the server simply by looping through the array of items with the
name "subject". etc.
You need to use input array like:
<input type="text" maxlength="10" name="attend[]" />
And then you will get all the values of attend in an array and you can loop through that $_POST['attend'].

POST arrays not showing unchecked Checkboxes

Having trouble getting my POST arrays to show all checkbox values from my form.
I have a form set up as follows:
<form name='foo' method='post' action=''>
<table>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
</tr>
</table>
</form>
I have a button at the bottom bound to a jquery function that adds 5 more empty rows to the form (hence the arrays for the input name cBox[]).
Now, the problem. Lets say the first checkbox is unchecked, and the last 2 are checked. When I output the values (using PHP print_r for debugging), I will get:
Array ( [0] => on [1] => on)
For some reason, the array does not contain any value for unchecked checkboxes.
I have seen some solutions where a hidden variable is passed with each checkbox, but can this solution be implemented in my situation (using arrays)?
That behavior is not surprising, as the browser doesn't submit any value for checkboxes that are unchecked.
If you are in a situation where you need to submit an exact number of elements as an array, why don't you do the same thing you do when there's an id of some sort associated with each checkbox? Just include the PHP array key name as part of the <input> element's name:
<tr>
<!-- NOTE [0] --->
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[0]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[1]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[2]'/></td>
</tr>
That still leaves you with the problem that unchecked boxes will still not be present in the array. That may or may not be a problem. For one, you may really not care:
foreach($incoming as $key => $value) {
// if the first $key is 1, do you care that you will never see 0?
}
Even if you do care, you can easily correct the problem. Two straightforward approaches here. One, just do the hidden input element trick:
<tr>
<td class='bla'>
<input type="hidden" name="cBox[0]" value="" />
Checkbox: <input type='checkbox' name='cBox[0]'/>
</td>
</tr>
<tr>
<td class='bla'>
<input type="hidden" name="cBox[1]" value="" />
Checkbox: <input type='checkbox' name='cBox[1]'/>
</td>
</tr>
And two, which I find preferable, fill in the blanks from PHP instead:
// assume this is what comes in:
$input = array(
'1' => 'foo',
'3' => 'bar',
);
// set defaults: array with keys 0-4 all set to empty string
$defaults = array_fill(0, 5, '');
$input = $input + $defaults;
print_r($input);
// If you also want order, sort:
ksort($input);
print_r($input);
See it in action.
ONE TRICK is to override the checkbox value, if checked. otherwise its value will be 0.
<form>
<input type='hidden' value='0' name="smth">
<input type='checkbox' value='1' name="smth">
</form>
Try
<input type='checkbox' value="XXX" name='cBox[]'/>
<input type='checkbox' value="YYY" name='cBox[]'/>
<input type='checkbox' value="ZZZ" name='cBox[]'/>
Checkboxes work that way. If it is checked, only then the value is posted.
If you are handling dynamic checkbox array, you can try this:
HTML:
<label>
<input type="hidden" name="cBox[]" value="" />
<input type="checkbox" class="checkbox" value="on" />
</label>
<label>
<input type="hidden" name="cBox[]" value="" />
<input type="checkbox" class="checkbox" value="on" />
</label>
<!-- extend -->
Javascript (jQuery):
$(document).on("change", "input.checkbox", function() {
var value = $(this).is(":checked") ? $(this).val() : null;
$(this).siblings("input[name='cBox[]']").val(value);
});
Backend result (If only checked the second one):
// PHP $_POST['cBox']
Array
(
[0] =>
[1] => on
)
In this implement, the checkboxes are used to controller each hidden input in a group.
For displaying page, You can render each inputs pair back by assigning the value into hidden inputs and marking checkboxes as checked.
Try setting a value to each checkbox, of 1 or true.
<input type='checkbox' value='1' name='cBox[1]'/>
that may be why its not sending anything?
In controller:
request()->merge(['cBox' => request()->input('cBox', [])]);

Categories