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;
}
Related
I dont know how to manage this situation, I'm a noob coder, I have a page that shows you all available lots where you can unload a specific item from that lot.
This is the foreach that prints out:
$lotto, $totalelotto, $data, and ask for qtyvalue to unload from $lotto (input can be also NULL)
foreach ($dataslotto as $data) {
$totalelotto = totlotto($database, $data['lotto']);
$lotto = $data["lotto"];
$data = $data["data"];
echo "<tr>";
echo "<td>".$lotto."</td>";
echo "<input type=\"hidden\" value=\"".$lotto."\" name=\"array[]\" />";
echo "<td>".$totalelotto."</td>";
echo "<input type=\"hidden\" value=\"".$totalelotto."\" name=\"array[]\" />";
echo "<td>".$data."</td>";
echo "<input type=\"hidden\" value=\"".$data."\" name=\"array[]\" />";
echo "<td><input type=\"text\" class=\"form-control\" placeholder=\"Qta.\" required name=\"qtyvalue\"></td>";
echo "</tr>";
}
I dont know how to set name="" of input fields (because the number of fields can change if there are many lots) and I dont know how to send $_POST data as array, and then foreach group of $lotto, $totalelotto, $data, $qtyvalue where is set $qtyvalue do another query.
I put it in no regular code, I know it looks bad but it's just for giving you an idea.
$_POST[''formarray];
foreach ( /* values recieved in each <tr> inside formarray where $_POST['qtyvalue'] is not empty */ ){
#EXECUTE THIS
}
Thanks for help!!
And sorry for my bad coding skills.
$_POST is an Associative/Key Value pair, it's key is whatever is set as the inputs name.
so if you wanted to send the users input username to the backend PHP script
You set the value and it's name
<input type="text" name="username" value="User123">
then to retrieve the user name you can do
print_r($_POST["username"]);
to print the value.
So you ask how do you loop over each one in $_POST, that's pretty simple you can could a foreach loop over the entire $_POST array.
foreach($_POST as $key => $value)
{
//check something has been entered for the current value we are iterating over
if($value != null)
{
print_r($key . " value is : " . $value);
}
}
this would loop over each item in the $_POST array with key being set to whatever the DOM elements name is.
Don't forget the $_POST array is just that an array, you could do
var_dump($_POST);
and see everything that was sent in the POST request.
You can use array names for your inputs. Say you have a row of your table like this:
<tr>
<td><input ... name="lotto[]"></td>
<td><input ... name="totalelotto[]"></td>
<td><input ... name="data[]"></td>
<td><input ... name="qtyvalue[]"></td>
</tr>
Then you will get arrays $_POST['lotto'], $_POST['totalelotto'] and so on, each with the same number of elements, and elements with same index belonging to one row of the table. You could then process those elements like this
foreach ($_POST['lotto'] as $i=>$lotto) {
if ($_POST['qtyvalue'][$i] > 0) {
...
}
}
I am creating a wordsearch, I'm trying to post the value in another page, The problem is that I cannot display all the value of $thisChar to another page, all I get is the last letter. So the question is how can you post a variable that is something like this e.g., $rc[$r][$c]...
This is my form. I have hidden fields that named thisChar.
echo '<form method="post" action="#path" target="blank">';
echo '<table>';
#--Display the random letters and the words
for ($r=0;$r<=$row;$r++) {
echo '<tr>';
for ($c=0;$c<=$col;$c++) {
$thisChar=strtoupper($rc[$r][$c]);
echo '<input type="hidden" name="thisChar" value="'. $thisChar.'">';
echo '<td style="background:#fff">' . $thisChar . '</td>';
}
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="submit">';
echo '</form>';
This is how I fetch the post data. All I get is Uninitialized offset error.
for ($r=0;$r<=$row;$r++) {
for ($c=0;$c<=$col;$c++) {
$thisChar=$_POST['thisChar'];
$pdf->Cell(10,10, strtoupper($thisChar) ,1,0,'C', );
}
}
I already tested other approach like foreach loop and adding square brackets on the name of hidden fields and it works, now I want to make it work using this approach. This method creates a loop that can display in a table. Any idea how can I make it works?
You need to post it as array, so your name attribute should look like this:
echo '<input type="hidden" name="thisChar[]" value="'. $thisChar.'">';
haven't check the rest of your code, but this will send all the values as an array
Use html input name as an array!
echo '<input type="hidden" name="thisChar[]" value="'.$thisChar.'">';
Then retrieve this variable in action PHP file as array:
$thisChars=$_POST['thisChar'];
foreach($thisChars as $thisChar)
{
...
}
i have send the value dynamically from check-box and when i tried to retrieve all the value dynamically using loop, it just goes on loading.
my code for sending value from check-box:
while ($row=mysql_fetch_array($query))
{
$member_id=$row["member_id"];
<input type='checkbox' name='check' value='$member_id'>
}
// this is working. but when i try to fetch the data from checkbox from only where the tick is given it doesn't work. this is how i tried to fetch the data
while(isset($_POST['check']))
{
echo $_POST['check']."<br>";
}
The trick here is, when you have multiple checkboxes with the same name and you want to get all the checked values on the server side, then you need to add [] after the name of the checkbox field in the html, eg.
<input type='checkbox' name='check[]' value='$member_id'>
if you do this, then $_POST['check'] will be an array of all the checked elements. As pointed out by others,
while(isset($_POST['check']))
represents an infinite loop. It should be
if(isset($_POST['check']))
foreach($_POST['check'] as $each_check)
echo $each_check;
And finally, its a duplicate of an existing question. Please search before asking again :)
You added While loop, with the condition that will always true. So loop will become infinite.
Change you loop to foreach, like this
foreach ($_POST['check'] as $value)
{
echo $value."<br>";
}
AND your check-boxes will not show till then you add echo, like this
while ($row=mysql_fetch_array($query))
{
$member_id=$row["member_id"];
echo "<input type='checkbox' name='check' value='$member_id'>";
}
if you want to get all the checkboxes
WRONG WILL CAUSE INFINITE LOOP
while(isset($_POST['check']))
{
echo $_POST['check']."<br>";
}
One of the many correct alternatives:
foreach ($_POST['check'] as $val) {
echo $val.'<br>';
}
foreach ($_POST['check'] as $selected) {
$selections[] = $selected;
}
print_r($selections);
and change your html tag as :
<input type="checkbox" name="check[]" value=".$member_id.">
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.
I am currently trying to design a for loop to iterate through any 'checked' check boxes, and from that, use the value within the 'value' slot to run some queries. I am unfortunately struggling with this as the list of checkboxes are not pre-defined, they are dynamic from the database pending the users previous selection.
The loop actually works to present the items to be checked:
?>
<input type="checkbox" name="option[]" value="$listing_id">
<font size="+1" color="green"><?php echo"$list_name"; ?>:</font><br />
<?php
The listing ID within the value is what I need to work with in a mysql query before I run an update query. The for loop that's meant to work is:
foreach($_POST['option'] as $option) //loop through the checkboxes
{
...
}
The update query will work within this as its simply copied from somewhere else, I just need the 'Listing_ID' from the check boxes that are checked.
I ran this code to hopefully do some debugging:
if(empty($_POST['option'])){
echo "no checkboxes checked.";
} else {
if(!isset($_POST['option'])){
echo "no set.";
}
}
and it returns "no checkboxes checked."
I have now hit a grey area as to why this for loop isn't working (this was taken from another example on the internet).
empty($_POST['option']) will return true, if either $_POST['option'] is not set (same as !isset($_POST['option']) (!)) or an empty array.
If you need to debug what's going on, use var_dump($_POST['option']); to find out what has been submitted for the option checkboxes. I also suggest you do a var_dump($_POST); so you can see what has been submitted overall - e.g. in case the post action is not post you will immediatly notice). For HTML output:
echo '<pre>', htmlspecialchars(print_r($_POST, true)), '</pre>';
That should give you the information you're looking for. For each individual checkbox, you can do:
foreach($_POST['option'] as $option) //loop through the checkboxes
{
var_dump($option);
}
First of all your code seems to be bugged to me. Maybe is just a typo but
<input type="checkbox" name="option[]" value="$listing_id">
should be
<input type="checkbox" name="option[]" value="<?=$listing_id?>"/>
Moreover using empty over an array is not good at all.
Try echoing out the $option in the loop to see what the value is and there you can see if there is something there.
foreach($_POST['option'] as $option) //loop through the checkboxes
{
echo $option . "<br />";
}
Also make sure your form's method is set to POST or that it's action is pointed to the correct place. You also have an error in your input:
<input type="checkbox" name="option[]" value="$listing_id">
I assume you meant:
<input type="checkbox" name="option[]" value="<?php echo $listing_id;?>">
UPDATE:
The error ended up not being in the code posted. Error was discovered in an if statement that always returned false that in-cased the code posted above.