Submit html table data with via form (post) - php

I want to post this html table on submit button click.
01 - I want to retrieve the data of this table in php code (server side)
02 - I also want to display this table on another page.
I'm using
PHP, JQuery
I have html table with many rows in form tag.
<form id="frm_test" class="form-vertical" method="post">
<table id="mytable">
<tr>
<td>
<input type="text" name="color_1" value="" />
</td>
<td>
<input type="text" name="color_2" value="" />
</td>
<td>
<input type="text" name="color_3" value="" />
</td>
<td>
<input type="text" name="color_4" value="" />
</td>
</tr>
......
......
......
......
.....
</table>
<input type="submit" name="submit" value="submit" />
</form>
===========
there are 4 input fields in each row (4 cells in each row). and hundred rows in table. So if I get value via name in php code then I have to write lot of code to get 100(rows) * 4 (input fields) = 400 inputs. So my question was "What is the best way to achieve this"

Since you are trying to submit multiple rows of inputs/selects with the same 'name' attribute to a backend, you would need to add square brackets [] to the end of the name value in those inputs (in the table rows).
<form>
<input type="number" name="examplevar" />
<table>
<tr>
<td><input type="text" name="color_1[]" /></td>
<td><input type="text" name="color_2[]" /></td>
</tr>
<tr>
<td><input type="text" name="color_1[]" /></td>
<td><input type="text" name="color_2[]" /></td>
</tr>
<table>
<input type="submit" />
</form>
This tells your browser to create an array for that name property.
In php, read it as $_POST['color_1'][0] and $_POST['color_2'][0], and loop as you'd like.
The brackets are in Phil Bailey's answer, but they are not pointed out.
(Added because a recent search led me to this)

To post a form you need to add the action tag which termines the path to go when the form is submitted
<form id="frm_test" class="form-vertical" name="THE_PHP_FILE_TO_POST.php" method="post">
When you want to POST values you should specify input fields with a certain name. If you only want the table is visible you should use the type hidden so the form will POST data, but the inputs aren't visible.
<tr>
<td>
My value
<input type="hidden" name="myValue" value="My value" />
</td>
</tr>
Once your form is posted you can catch the POST data in that PHP file like this:
//THE_PHP_FILE_TO_POST.php
if(isset($_POST))
{
$myValue = $_POST['myValue']; //Contains the string "My value"
//Do something with your POST
}
EDIT Get all table data
if(isset($_POST))
{
foreach($_POST as $inputName => $inputValue)
{
echo $inputName; //This is the name of an input field
echo $inputValue; //This is the value of the input field
}
}

PHP has a an odd naming convention for for table input fields you need to specify the name for the file as an array. For the following SQL Statement using PDO one processing method.
select id,color_1,color_2,color_3,color_4 from colors;
<?php
// Get data
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_NUM);
reset($results);
echo '<table>';
while (list(, $i = each($results)) {
echo '<tr><td><input type=hidden name="id[]" value="' . $i[0] . '"></td>';
echo '<td><input type=text name="color_1[]" value="' . $i[1] . '"></td>';
echo '<td><input type=text name="color_2[]" value="' . $i[2] . '"></td>';
echo '<td><input type=text name="color_3[]" value="' . $i[3] . '"></td>';
echo '<td><input type=text name="color_4[]" value="' . $i[4] . '"></td>';
echo '</tr>';
}
echo '</table>
?>
Simplified $_POST print_r output for 4 records:
Array ( [[id] => Array ( [0] => 20 [1] => 21 [2] => 44 [3] => 45 )
[color_1] => Array ( [0] =>red [1] =>green [2] =>yellow [3] =>blue )
[color_2] => Array ( [0] =>purple [1] =>orange [2] =>green [3] =>red )
[color_3] => Array ( [0] =>red [1] =>green [2] =>yellow [3] =>blue )
[color_4] => Array ( [0] =>purple [1] =>orange [2] =>green [3] =>red ) )

You need to add input field in your table to post data.
like
<input type="text" name="fieldname" value="" />
If you do not want to display field then you can make field hidden by using type="hidden"
Add action attribute in your form.
Action attribute indicates the url on which your data will be posted.

Related

store multiple value with same input name in sql

I need to insert the value of form into the data table.
here is my form for taking a test.
<form method="post" action="">
1<input type="text" name="answer">
3<input type="text" name="answer">
5<input type="text" name="answer">
7<input type="text" name="answer">
<input type="submit" name="submit">
</form>
how to store this all answer in one field of the data table
i have tried this code but its not storing all value
if(isset($_POST['submit']))
{
$answer = json_encode($_POST['answer']);
$query = "INSERT INTO `test` (`answer`) VALUES ('$answer')";
mysqli_query($con, $query);
if (mysqli_query($con, $query)) {
echo "inserted ";
} else {
echo "Error updating record: " . mysqli_error($con);
}
}
Try changing your HTML code to this.
<form method="post" action="">
1<input type="text" name="answer[]">
3<input type="text" name="answer[]">
5<input type="text" name="answer[]">
7<input type="text" name="answer[]">
<input type="submit" name="submit">
</form>
When you submit the form the $_POST['answer'] would look something like this
Array
(
[answer] => Array
(
[0] => first answer
[1] => second answer
[2] => third answer
[3] => fourth answer
)
)
Above is a printout of $_POST variable like so print_r($_POST)
Now you can easily get all the answer inputs inside PHP and have it converted to json like so
$answer = json_encode($_POST['answer']);
However since you are saving this inside mysql I would suggest using serialize() instead of json_encode(). Please read about serialize() https://www.php.net/manual/en/function.serialize.php

Multi-dimensional form $_POST data keys not set

This is how I display the entire array:
print('<pre>');
print_r($_POST);
print('</pre>');
The Array :
Array
(
[Prod] => Array
(
[0] => Array
(
['id'] => 1
['name'] => value2
['desc'] => value
['cost'] => 500.0000
['sell_price'] => 1500.0000
['quant'] => 9
['vendor'] => 1002
['last_update'] => Joe Lee
)
[1] => Array
( ... )
['btnUpdate'] => Sumbitted Form
)
)
but if I change it to $_POST['Prod']['btnUpdate'] it throws an error..
This is how the Error if I try to access "btnUpdate"
Notice: Undefined index: btnUpdate in
C:\xampp\htdocs\Projects\Upwork\dharn\scratch\phase2\controller\update_Product.php
on line 6
I've read the duplicate but as you can see the entire array of $_POST.. in my knowledge $_POST['Prod']['btpUpdate'] should exist but NO it does not, php can't find it...
UPDATE
i've made a type mistake on creating the array..
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<input type="text" hidden name="Prod[<?php echo $x?>]['id']" value="<?php echo $row['id']?>">
<?php echo $row['id']?>
</td>
<td>
<input type="text" name="Prod[<?php echo $x?>]['name']" value="<?php echo $row['name']?>">
</td>
<td>
<input type="text" name="Prod[<?php echo $x?>]['desc']" value="<?php echo $row['description']?>">
</td>
<td>
<input type="text" name="Prod[<?php echo $x?>]['cost']" value="<?php echo $row['cost']?>">
</td>
<td>
<input type="text" name="Prod[<?php echo $x?>]['sell_price']" value="<?php echo $row['sell_price']?>">
</td>
<td>
<input type="text" name="Prod[<?php echo $x?>]['quant']" value="<?php echo $row['quantity']?>">
</td>
<td>
<select name="Prod[<?php echo $x?>]['vendor']">
<?php echo Generate_Vendor($row['Vendor_name']); ?>
</select>
</td>
<td>
<input type="text" hidden name="Prod[<?php echo $x?>]['last_update']" value="<?php echo $row['Employee_name']?>">
<?php echo $row['Employee_name']?>
</td>
</tr>
<?php
$x++;
}
?>
</table>
<button type="submit" name="Prod['btnUpdate']" value="'Sumbitted Form'"> Update Product </button>
ANSWER
in a code like this name="Prod[<?php echo $x?>]['id']" right in the id part... that's the typo.. you should not put ( ' ' ) single-qoute on the array because it will generate an array like the one above where you could not access it because it is a string inside the key...
in simple words you should not create an array with a stringed key
The error here was that I was creating a parameterized array in a multi-Dimensional Array using brackets..
If you ever create a parameterized array don't do this
<input name="person['name']" ...
this wont work because the quotes are included in the key in the array.
To access these keys, you would need something like
$_POST['person']["'name'"]
which is unintuitive. Keys in form element names should only be an index like 0,1,2,3 or a word but not a quoted string.
Do it like this instead
<input name="person[name]" ...

PHP post two values in one field, one of which is hidden

Is there a way that I can post two values at the same time from a single field in a table but hide one from the user?
I would like the following form to post the values ID and reason_name when it is submitted but have the user only be able to see (and edit in the text box) the reason_name.
<form name="add_positioning" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table border="1" class="autoTable_pos">
<tr>
<td>Positioning</td><td> </td></tr>
<?
$sql= "SELECT * FROM gradeReason WHERE reason_userID = $user_id AND category = 'positioning' AND current = 1";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="text" name="reason[]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<?
}
?>
<tr>
<td>
<input type="text" name="reason[]" size="25"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Save" name="save_reasons"/>
</td>
</tr>
</table>
</form>
The form POST action so far (basic echo at the moment for my own sanity to check that it posts the values correctly, which it does...)
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $item) {
echo $item.'<br/>';
}
}
This table displays the values that are held in a database but enables the user to add more values by dynamically adding a new row (using JQUERY I haven't included) to the table when they type in an empty one at the bottom and also allows them to edit or delete existing values.
For each value posted I intend to check if the ID value is empty, if it is it means that it is a new value and enter a new record into the database, if it isn't update the existing record in the database with the corresponding ID. I don't have a problem writing that bit, I just can't think how to get the ID value posted as well as the reason_name while keeping ID hidden from the user.
Add the ID to the name attribute of the Text boxes of the reasons loaded from the DB. Leave the other Text boxes added using JQ without the ID.
E.g.
Text box which shows the existing reason loaded from the DB
<input type="text" name="reason[][ID]" size="25"/>
Text box added with JQ
<input type="text" name="reason[]" size="25"/>
Then once you submit the form you get you will get the following array.
array
'reason' =>
array
0 =>
array
14 => string 'VAL1' (length=4)
1 => string 'VAL2' (length=5)
By checking for an array in the each element in the "reason" array, you can differentiate two type of Text Boxes.
Here is the complete code I have tested.
<?PHP
//var_dump($_POST);
foreach($_POST['reason'] as $item=>$value)
{
if(is_array($value)){
foreach($value as $ID=>$reason)
{
echo "Existing Reason : ".$ID." - ".$reason."<br>";
}
}
else{
echo "New Reason : ".$item." - ".$value.'<br/>';
}
}
?>
<form action="" method="POST">
<input type="text" name="reason[][14]" size="25" value="aaaa"/>
<input type="text" name="reason[]" size="25" value="bbbbb"/>
<input name="" type="submit">
</form>
Assuming the id is at $row['reason_id'] I think you want:
$i = 0;
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="hidden" name="reason_id[<? echo $i; ?>]" size="25" value="<? echo $row['reason_id']; ?>"/>
<input type="text" name="reason[<? echo $i; ?>]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/></td></tr>
<? $i++ } ?>
This way you can later
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $key => $item) {
$id = $_POST['reason_id'][$key];
echo $id . " " . $item.'<br/>';
}
}

Extra added field value to be sent in post method

After adding the extra field using javascript, the extra field values are not being sent by post method in php. Here in the code adding the basic 5 fields, rest are the extra fields that user can add if necessary
The code is as follows:
<script language="javascript">
var i = 11;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<tr><td> <input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/></td><td><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/></td><br/></tr>";
i++;
}
</script>
<body>
Please enther the grocery items
<table>
<tr>
<th> Item name</th><th> kg/No of packet</th>
</tr>
<form method="post" action="gl.php">
<tr> <td><input id="item1" name="item1" type="text" maxlength="255" value=""/></td><td><input id="kgorp1" name="kgorp1" type="text" maxlength="3" value=""/></td></tr>
<tr> <td><input id="item2" name="item2" type="text" maxlength="255" value=""/></td><td><input id="kgorp2" name="kgorp2" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item3" name="item3" type="text" maxlength="255" value=""/></td><td><input id="kgorp3" name="kgorp3" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item4" name="item4" type="text" maxlength="255" value=""/></td><td><input id="kgorp4" name="kgorp4" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item5" name="item5" type="text" maxlength="255" value=""/></td><td><input id="kgorp5" name="kgorp5" type="text" maxlength="3" value=""/></td></tr>
<tr id="my_div"></tr>
<tr> <td><input id="saveForm" type="submit" value="Submit List" /></td><td><input id="addtxt" type="button" name="addtxt" value="Add more items" onClick="changeIt()" /></td> </tr>
</form>
</table>
</body>
The php code for retrieving the data sent via post method,
$i=1;
foreach ($_POST as $param_value) {
if ( empty( $param_value ) ) {
} else {
echo "<td>$param_value</td>";
if ( ( $i % 2 ) == 0 ) {
echo "</tr> <tr>";
}//echo $i;
}
$i++;
}
The problem is with how your form tag is placed and parsed in the HTML DOM.
Put the form tag higher in the document, after the tag.
<body>
Please enther the grocery items
<form method="post" action="gl.php">
and then change the javascript to this:
function changeIt()
{
var child = document.createElement('td');
child.innerHTML = "<input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/>";
document.getElementById("my_div").appendChild(child);
i++;
}
What you should get when you do a print_r($_POST) is:
Array ( [item1] => [kgorp1] => [item2] => [kgorp2] => [item3] => [kgorp3] => [item4] => [kgorp4] => [item5] => [kgorp5] => [item6] => [kgorp6] => [item7] => [kgorp7] => [item8] => [kgorp8] => [item9] => [kgorp9] => [item10] => [kgorp10] => [item11] => [kgorp11] => )
A better solution is to get rid of the table and tr/td tags and work with divs/spans for the form (its a lot nicer way to code, honestly :) )
Instead of using it in a function, simply put it inline inside your form in the following manner,
document.write('<input type="hidden" name="whatever" value="'+i+'">');
and make the adjustments necessary according to what you need.
for(i=0;i<=11;i++) {
document.getElementById("my_div").innerHTML = document.getElementById("my_div").innerHTML +"<tr>
<td> <input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/></td>
<td><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/></td>
<br/>
</tr>";
}
Demo
I don't see where the my_div variable is initialized.
You could do, in the beginning of your changeIt function:
var my_div = document.getElementById('my_div')
Then another problem: don't name this variable my_div while it's actually a tr tag.
And further: in this tr tag, your changeIt function will include HTML containing another tr, so you'll end up with bad HTML. A suggestion: do not use tables but instead, div or li tags for such a listing.

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