How do I pass rows from HTML form to PHP? - php

I'm written a PHP program to display a tab delimited file. The purpose of this is to allow the user to views the rows and select which ones they want by checking the checkbox given in the row for each record. After they hit submit I have a PHP program to display the values, but the problem is only the last row's ID is being passed. However, when the user hits the SUBMIT button I can see all the values for the rows checked:
process_form.php?download=5108&download=5110&download=5114
How should I parse this in process_form.php? I've done a var_dump of $_POST and also
$_REQUEST but it only shows the last value which is 5114. I kind of understand the problem, most of the time in forms programmers only get one value per input field, but what happens when there are many records? It doesn't seem they should all have their own unique 'name'.
<td align=center><input type="checkbox" name="download" value="<?php echo $row['ID']; ?>"></td>
I'm doing something wrong here, but I'm not sure what. Is there a way to pass an array (I'm guessing) of IDs? Or should I be looking at parsing the URL of ?download=5108&download=5110&download=5114 because it has all the values I need there? If so, how do I do that? Thanks!

This is my solution:
<td align=center><input type="checkbox" name="download[]" value="<?php echo $row['ID']; ?>"></td>
Notice that download is now download[], thus creating an array to be passed to the PHP program to process the form.
Then using this demo PHP code I was able to get access to the array:
$my_array = ($_REQUEST["download"]);
print_r($my_array);
echo "<P>";
foreach ($my_array as $value)
{
echo $value . "<BR>";
}

I'd rather use your rowID to identify the name of <input> instead of the value.
<td align=center><input type="checkbox" name="download_<?php echo $row['ID']; ?>" value="1"></td>
Then you can process your request array like:
foreach( $_REQUEST as $key => $value ) {
if( preg_match('/^download_([0-9]+)$/', $key, $reg ) {
$rowId = $reg[1]; // Your row ID
$isChecked = $value; // State of checkbox
}
}
The row ID is parsed from variable name using regexp.
EDIT:
As mentioned in comments, this is not the simplest way to read an array of checkboxes. The simpliest is to name checkboxes download[] and parse this array in PHP then.
However, this is more universal, for example when you need to get array of input texts instead of checkboxes.

Related

Php : Post a list of checkboxes

After a SQL request, I obtain a form which contains a list of data, with checkboxes at the end of each line. The goal is the following. If the user checks some of them, the line will be deleted in the database when the form will be submitted.
I name my checkboxes like this, with my SQL request results, so my Php script could find the line to delete:
<input type="checkbox" name="chk[<?echo '/'.'$t[datetr]'.'/'.'$t[beneficiaire]'.'/'.'$t[objet]'.'/'.'$t[montant]';?>]">
My goal is to get all the checkboxes values with $_POST to my Php script. But even with this...
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
...my php script does not seem to get the checkboxes values... Did I do something wrong ? Thanks for help.
Aside from the other (entirely accurate) comments about unchecked boxes not being passed with the HTTP request - you have a couple of issues with your actual PHP.
<?echo '/'.'$t[datetr]'.'/'.'$t[beneficiaire]'.'/'.'$t[objet]'.'/'.'$t[montant]';?>
Firstly, your echo is wrong; it should probably be <?php echo or <?= rather than <?echo (although that might work with short start tags enabled).
Secondly, Apostrophes in PHP are non-interpolated string literals (i.e. '$t[objet]' will literally be treated as the string '$t[objet]' not the variable).
Finally, assuming $t is an array, your associative indexes need to have quotes or they'll be interpreted as constants - which is likely to throw an error.
I think what you want could be written as:
<?= "/{$t['datetr']}/{$t['beneficiaire']}/{$t['objet']}/{$t['montant']}"; ?>
Once you've sorted that out, the $_POST['chk'] data should be set properly and it'll be an associative array as you're expecting.
Then a foreach($_POST['chk'] as $key => $value) { ... } loop should work... though, of course none of your inputs actually have values at the moment.
When using <input type="checkbox" name="foo" value="42"/>, the variable foo=42 is sent only if the checkbox is checked. When the box is not checked, nothing is sent at all.
If you need some 0/1 information, i suggest you use either a <select> or a couple of <input type="radio"> tags instead:
<input type="radio" name="foo" value="1"/> Yes
<input type="radio" name="foo" value="0"/> No
Blank checkboxes do not get posted to the receiving script, only checked ones do. To get around this have a corresponding set of hidden fields, and set their values to something like "ON" or "OFF" depending on how the checkboxes are clicked. You will probably want to use the onClick event, determine of the box is clicked or not then set the appropriate hidden field, i.e.
Checkbox_One Hidden_One
Checkbox_Two Hidden_Two etc.
When you post the form, have your script ignore the checkboxes, and just process the hidden fields.
Something to remember when doing these multi-checkboxes is that when you submit, it will be interpreted in PHP as an array, in your case $_POST['chk'] will be an array of checked checkboxes.
However, you should also make sure you give the checkboxes a value, even if just a 1.
When handling your POST, initially just try using a var_dump($_POST); die(); to see what the data looks like.
use the code below:
foreach ($_POST['chk'] as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
If you name all your checkboxes like this name="boxArray[]" it will create an array named $_POST["boxArray"] when the form is submitted.
Then you can do your foreach loop to display the values:
foreach ($_POST["boxArray"] as $item) {
echo "<tr>";
echo "<td>";
echo $item;
echo "</td>";
echo "</tr>";
}
To add to this, if you want to delete only the items checked then for each checkbox assign the record's ID as its value:
<input type="checkbox" name="boxArray[]" value="RECORD ID">
Now when you run your foreach loop only the checked boxes will post values so you change the code to delete each item in the array:
foreach ($_POST["boxArray"] as $item) {
//SQL TO DELETE RECORD WHERE ID = $item;
}

submit all users values from form into db

This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];

Creating and Storing an array / Dynamic array

I have issues with creating an array and storing the info, I have a table with data that could be infinite in its number, a user will then select some options which will determine which of these values they can select (which again is an infinite number), these choices are then presented into a checkbox where i use this code
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details" value="'.$invoice_details.'"/>';
}
?>
So this should search through the options they previous choose, and sorts them into an array and then into checkboxs, but when i store the information is just saves the last box checked, I cant change the value of each input EG
echo '<input type="checkbox" name="invoice_details[value1]"
echo '<input type="checkbox" name="invoice_details[value2]"
Because I don't know how many values/checkboxes there will be.
I have also tried this
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details[] = $detailsline->details_line;
echo $invoice_details[];
echo '<input type="checkbox" name="invoice_details[]" value="'.$invoice_details.'"/>';
}
?>
Changing the
$invoice_details
to
$invoice_details[]
but this will just store a value "Array" in my database and not the actual values.
Please can anyone help me?
Ian
Okey I think You should Try this:
<?php
$i=0;
foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details[$i]" value="'.$invoice_details.'"/>';
$i++;
}
?>
Try this
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details[]" value="'.$invoice_details.'"/>';
}
?>
Use <input type="checkbox" name="invoice_details[]">
In your code you can use serialize($invoice_details) for saving into DB and when using - unserialize($field_from_db).
First function returns string, so you can save it as string field, second function get the string and returns the whole array, so you can work with it.
but this will just store a value "Array" in my database and not the actual values.
think you tried to store Array as string so got that value
So may be needed to use implode/serialize/json_encode (Array) to store data?
Literally saying code $invoice_details[] = $detailsline->details_line; means take property details_line of an object $detailsline and insert its value as new element in array $invoice_details. Are you sure it is what you want?) Also I suppose that $detailsline is an array, but not the object (you trying to operate it as an object)

Return value from element while showing another

Hi lets say I'm showing a numeric value in an element (not sure what element to use), what i want to achieve is once the numeric value is clicked (Thinking of onclick="this.form.submit();" or submit button) it will submit different designated value from the numeric value let us say. Apple then my sql query would retrieve apple and use it. NOTE: I have multiple numeric values and multiple designated values for each numeric value as an example it looks like this:
(numeric value) = (designated value)
15123 = apple
24151 = orange
39134 = peach
Here so far is what i have.
<input type='submit' name='searchthem' placeholder='<?php echo $numeric_value; ?>'
value='apple'>
** NOTE i have multiple numeric values with different designated value
And this is the SQL in the same page:
SELECT * from tbl_fruits where fruit_name='".$_POST['searchthem']."' ;
Would appreciate some help and ideas, If there is confusion please comment so i may further clarify.
Use select element and just submit the form so that it can process the values. if you wish to use AJAX, use some javascript and output the result in the browser.
If I understand your problem correctly you should add an array for the definition terms and do it like this:
<input type="hidden" name="searchterm" value="<?php echo $numeric_value; ?>" />
<input type='submit' name='send' value="<?php echo $names[$numeric_value]; ?>" />
Then in PHP switch through the values:
switch($_POST['searchterm']){
case(15123) $term = 'apple';break;
case(24151) $term = 'ornage';break;
case(39134) $term = 'peach';break;
}
This will secure your SQL query, too. [Beware: Never use unfiltered input (i.e. $_POST in your example) from the browser in SQL queries!]

Extract dynamically created form data

I've just started using jQuery. One thing I've been using it for is adding rows to a table that is part of a form.
When I add a new row, I give all the form elements names like 'name_' + rowNumber. I increment rowNumber each time I add a row.
I also usually have a Remove Row Button. Even when a row is removed, the rowNumber count stays the same to keep from repeating element names.
When the form is submitted, I set a hidden element to equal the rowNumber value from jQuery. Then in PHP, I count from 1 to the rowNumber value. Then for each value, I perform an isset($_REQUEST['name'_ . index]). This is how I extract the form elements that remained after deleting rows in jQuery.
Does anyone here have a better technique for accounting for deleted rows?
For some of our simpler tables, we use a field name such as 'name[]', though for JavaScript they would need a usable id.
It does add some complexity in that 'name[0]' has to assume 'detail[0]' is the correct element.
PHP will create an array and append elements if the field name ends with [] similar to
<input name="field[]" value="first value" />
<input name="field[]" value="second value" />
// is roughly the same as
$_POST['field'][] = 'first value';
$_POST['field'][] = 'second value';
Use arrays to hold you values in your submission. So bin the row count at the client side, and name your new elements like name[]. This means that $_POST['name'] will be an array.
That way at the server side you can easily get the row count (if you need it) with:
$rowcount = count($_POST['name']);
...and you can loop through the rows at the server side like this:
for ($i = 0; isset($_POST['name'][$i]; $i++) {}
You could extract all the rows by doing a foreach($_POST as $key => $value).
When adding a dynamic form element use the array naming method. for example
<input type="text" name="textfield[]" />
When the form is posted the textfield[] will be a PHP array, you can use it easily then.
When you remove an element make sure its removed from the HTML DOM.
Like blejzz suggests, I think if you use $_GET, then you can just cycle through all of the inputs that were sent, ignoring the deleted rows.
foreach ($_GET as $k=>$v) {
echo "KEY: ".$k."; VALUE: ".$v."<BR>";
}
I notice that you mention "accounting for deleted rows"; you could include a hidden input, and add a unique value to it each time someone deletes a row. For example, the input could hold comma-separated values of the row numbers:
<input type="hidden" value="3,5,8" id="deletions" />
and include in your jQuery script:
$('.delete').click(function(){
var num = //whatever your method for getting the row number
var v = $('#deletions').val();
v = v.split(',');
v.push(num);
v = v.join(',');
$('#deletions').val(v);
});
Then you should be able to know which rows were deleted (if that is what you were looking for).
you can use POST or GET
After submit you can use all of your form element with this automaticly. You dont need to reorganise your form element names. Even you dont need to know form elements names.
<form method="POST" id="fr" name="fr">.....</form>
<?php
if(isset($_POST['fr'])){
foreach($_POST as $data){
echo $data;
}
}
?>
Also you should look this
grafanimasyon.blogspot.com.tr/2015/02/veritabanndan-php-form-olusturucu.html
This is a automated form creator calcutating your database tables. You can see how to give name to form elements and use them.

Categories