Catching data from multiple checkboxes in a POST request - php

Many thanks for checking this question. I have a simple email system on my website between users. Below is a section of code which is a foreach loop pulling out each email in a users inbox and displaying the subject and author etc. I have a delete checkbox to go with each one. I am struggling to see how I get catch the emails that have been selected for deletion in a POST request. I am thinking that it probably involves an array but not sure. All checked boxes have the same value of 'delete' so it should be easy enough, but I can't find a solution
<!-- LOOPING THROUGH ALL THE RESPONSES TO THE GIVEN THREAD -->
<?php foreach($messages as $message):?>
< div class="message_strip">
<table>
<tr>
<td>
<?php $id = $message->sender_id;?>
<img style="width:30px; margin:2px;"
src="../<?php echo grab_thread_thumbnail($message->sender_id); ?>"/>
</td>
<td>
<div>
<?php echo $message->style_email($message->message_id);?>
<div class="sender">
<?php $user=User::find_by_id($message->sender_id);
echo htmlentities($user->first_name);?>&nbspwrote on
<?php echo datetime_to_text($message->time); ?>
</div>
</td>
<form action="message_folder.php" method="post">
<td class="delete_checkbox">
<input type="checkbox" class="cb-element" name="delete" value="delete">
</td>
</form>
</tr>
</table>
</div>
</a>
<?php endforeach; ?>

Don't wrap the checkbox input in the form tags. Wrap your entire foreach in the form tags, and you'll need a submit button.
Assuming you want the message_id:
<input type="checkbox" class="cb-element" name="delete[]" value="<?=$message->message_id ?>">
Then you will have an array of message_ids that were checked in $_POST['delete'].

You need to give each checkbox a unique name, e.g. name='delete[$message->sender_id]', then iterate over the POST'ed array.

Related

When submitting this button inside a datatable doesnt submit the right row id

I have a dynamic table which is set inside a foreach, so for each item of the array fetched create a new row. I have in the last column a button for each row. When clicking that submit button I am suppose to receive the id of that in PHP. Submission is being done correctly, but I am receiving the wrong id in PHP. Its basically taking the last id of the array when submitting. Any idea why?
Here is the table:
<form method="post" id="frm-example" action="<?php echo $_SERVER["PHP_SELF"] . '?' . e(http_build_query($_GET)); ?>">
<table id="example" class="display compact">
<thead>
<th>Device</th>
<th>Sales date</th>
<th>Client comments</th>
<th>Breakage count</th>
</thead>
<tbody>
<?php foreach ($arr_cases_devices as $cases) { ?>
<tr>
<td>
<?php echo $cases['name']; ?>
</td>
<td>
<?php echo $cases["sales_date"]; ?>
</td>
<td>
<?php echo $cases["dev_comment"]; ?>
</td>
<td>
<input type="hidden" name="device_id_breakage" value="<?php echo $cases["Dev_Id"]; ?>" />
<button type="submit" name="see_rma">See RMA</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
When clicking on see_rma this is what I receive in PHP:
if (isset($_POST['see_rma'])) {
$selected_dev = e($_POST['device_id_breakage']);
print_r($selected_dev); // prints the "Dev_Id" of the last row, not of the row clicked
}
If I try printing $cases["Dev_Id"]; inside loop in the table, it prints perfectly fine, so it prints the Dev_Id of each row correctly. So, that means there is nothing wrong with the array or data. I don't why is this happening but it's for sure the first time I am having this issue.
I do this in many other tables but for some reasons in this one its not working properly.
You have multiple <input> elements with the same name within your form, and all of them are going to be submitted when you submit the form, but PHP can only get one of them. That's why you end up with only the last one in $_POST.
It looks like you should be able to fix this by just moving some attributes from the hidden input into the button (replacing the hidden input).
<button type="submit" name="device_id_breakage" value="<?php echo $cases["Dev_Id"]; ?>">
See RMA
</button>
Only the button that was clicked will be submitted. Note that after changing the name of the button, you won't have see_rma in $_POST any more, so if you have any code that depends on that you'll need to change it to look for the other name instead.

Update a value in a table using checkbox in PHP

I'm a beginner in php and I have a problem regarding checkbox.
First thing is that, in the form I don't know if name=medID[] is specifically used as an array. or a normal string like medID will work? and how exactly is it useful to use an array.?
When I'm updating the value in query both $quan and $medID values are not passing in the query.
In browser it shows "Alloted Succesfully" but the database value of quantity is not changing. when i replace $quan and $imp value to some integers then it works fine.
<tbody>
<tr>
<form method="post" action="ytube.php?array=hospitalstock&hospitalID=<?php echo $opened['hospitalID']; ?>&id=allot" role="form">
<div class="form-group">
<td class="vcenter"><input type="checkbox" name="medID[]" id="check" value="<?php echo $list['medID']; ?>" /></td>
</div>
<td><?php echo $list['item'] ?> </td>
<td><?php echo $list['price'] ?> </td>
<td><?php echo $list['quantity'] ?> </td>
<td><?php echo $list['subtotal'] ?> </td>
<div class="form-group">
<td><input type="text" name="quantity" id="quantity" class="form-control" /> </td>
</div>
</tr>
<?php }} ?>
<div class="form-group">
<input class="submit" type="submit" value="Allot Medicine" name="submit" class="form-control" />
</div>
</form>
</tbody>
</table>
<?php
$id=$_POST['medID'];
$quan=$_POST['quantity'];
if(isset($_POST['submit'])){
if(empty($id) || $id==0){
echo 'Select medicines to allot ';
}else{
echo $quan;
$imp= implode(", ",$id);
$q="UPDATE hospitalstock SET quantity= (quantity - '.$quan.') WHERE medID IN('.$imp.')" ;
$r=mysqli_query($conn, $q);
if(isset($r)){
echo 'Alloted Succesfully';
}
}
}
?>
Yes a normal string like madID will work just aswell.
name="medID" => $_post['medID']
name="medID[]" => $_post['medID'][0] de last [0] will get you the first element of the array
An array could be really helpful when it's a dynamically created form. A form where the number of inputs is not set, for example a contact form where you can click on a plus icon to add another text input for multiple phone numbers. Bacause its unknown how many phone numbers someone have its easier to just retrieve one variable as an array and iterate over this array after.
Don't you get an error like:
Notice: Undefined index: medID in ....
In your code you have name="medID[]" and $_post['medID']. So your form is sending an array but you retrive a normal variable. Just delete [] from name="medID[]"
Because of that if(empty($id) $id will always be empty so you don't even reach your query.
Few things to say; first I don't understand the concept of using a query string for action when you are using post as a method for submitting the values. Secondly if you are trying to consume the values from the query string as well; then I can't find the $_GET[] in your entire program. Third is a suggestion to use $_REQUEST[] when you are not sure about the get or post collections. Also, the name="medID[]" won't create any array for PHP. Is the ytube.php the same page where you have created this form?

getting values from table when checkbox is checked php

I have this code to show my table:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<table cellspacing='0'>
<?php
if(isset($_GET["ordem"])){
if($_GET["ordem"] == 'descendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo "</tr></thead>";
}
elseif($_GET["ordem"] == 'ascendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=descendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação </th>";
echo "<th>Enviar mail</th>";
echo ("</tr></thead>");
}
}
else{
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=ascendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo("</tr></thead>");
}
while($stmt->fetch()){
echo("<tbody>");
echo("<tr><td>$nomeUser</td>");
echo("<td>$email</td>");
echo("<td>$nomeVoucher</td>");
echo("<td>$categoria</td>");
echo("<td>$preco</td>");
echo("<td>$confirmacao</td>");
$content = file_get_contents($file,$filePDF);
echo("<td><INPUT TYPE='checkbox' NAME='mail[]' multiple='yes'></td>");
echo("</tr>");
echo("</tbody>");
}$stmt->close(); ?>
I have a checkbox in my table and I would like to know how can I get the values of each rows from the table when i selected the checkbox. I want to send email when the user selected multiple checkbox.
Thanks
It's possible that the code above is a snippet of a larger page, but if not:
You aren't actually wrapping your input elements in an HTML form tag. Doing so will cause the user agent (presumably a browser) to treat each input tag as something to be submitted to your backend form.
You should wrap the tables in a table element; tbody is a child of a table.
Regardless of the above:
It looks like your PHP code above will render the entire tbody each time the statement fetches a new row, which is a bit weird. I'd assume you only want to render a row containing mail options?
To the best of my knowledge, there is no multiple attribute allowed in a checkbox element. You may be thinking of the select element.
You are not setting a value attribute on your checkbox input tag. If the user actually submits a form, you'll either get a set of empty mail[] variables, or nothing at all, I'm not actually sure which.
Consider the code below: Note that the checkboxes have the same name attribute, but different values.
<form method="post">
<table>
<tbody>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val1" id="mail-val1" />
<label for="mail-val1">Value 1</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val2" id="mail-val2" />
<label for="mail-val2">Value 2</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val3" id="mail-val3" />
<label for="mail-val3">Value 3</label>
</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
Given this form, if the user selects all three of the checkboxes and submits, your server will receive a POST request with the payload:
mail[]=val1&mail[]=val2&mail[]=val3
Depending on how PHP parses that response (it's been about a decade since I've dealt with PHP), you'll probably have an array variable accessible to your application:
# mail == ["val1", "val2", "val3" ]
Hope this helps.

process hidden field with jquery and calculate

I have an html table I've updated to use checkboxes to be able to delete multiple files:
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Date Created</th>
<th>Video Size</th>
<th>Video Length</th>
<th>
<button type="submit" class="deletebutton" name="delete_video" value="Delete" title="Delete the selected videos" onClick="return confirm('Are you sure you want to delete?')">Delete</button><br>
<input type="checkbox" name="radioselectall" title="Select All" />
</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
//do stuff
//Note: I'm looping here to build the table from the server
?>
<tr >
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo setlocalTime($result_videos[$i]["video_datetime"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo ByteSize($result_videos[$i]["video_size"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="checkbox" name="radioselect" title="Mark this video for deletion"/>
<input type="hidden" name="video_name" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
</form>
</td>
</tr>
I started with first creating some jquery code to create a select all/deselect all button in the table heading and just a test to show I can find which boxes are checked. That all works:
//selectall checkboxes - select all or deselect all if top checkbox is marked in table header
$("input[name='radioselectall']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","td").attr('checked',true);
}
else
{
$("input[type='checkbox']","td").attr('checked',false);
}
});
//process checkboxes - which ones are on
$(".deletebutton").click(function() {
$("input[name='radioselect']:checked").each(function(i){
alert(this.value);
});
});
So the part where I'm stuck is I don't know where to go from here. I need to pass all the video_names of all the videos selected (with the checkboxes). video_name is part of a hidden field in my form. So I need to pass that to my php function when the delete button is selected. Not really sure how to tackle this. Hope this makes sense.
Simple solution maybe:
Change your checkboxes to have a value of 1 and a name of $result_videos[$i]["video_name"]; in the table rows, make the form encapsulate the whole table.
Then on submit you can do something like:
foreach ($_POST as $key => $value) {
//Delete $key (the name) where $value == 1
}
Your approach is fine if you want to access the hidden fields through jQuery at a given point but once you submit the form and lose the DOM, the PHP processing page will have no way to relate the selected checkboxes with the hidden fields as there is no consistent naming scheme.
One approach would be to use the loop counter to suffix the two in order to pair them up:
<input type="checkbox" id="radioselect_<?= $i ?>" title="Mark this video for deletion" value="1" />
<input type="hidden" id="video_name_<?= $i ?>" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
This would be good if you want to relate more than the two fields. Otherwise, you could just use the video_name as the value of the checkbox, as Ing suggested.

How to handle a dynamic table with dojo.query()

This is going to be a meaty question because I am not sure the best way to handle this.
I have a page that contains a number of dojo inline editors, to allow users to change values, when one entry had been changes a save button will appear to prompt the user to save the information.
The page has a number of rows, contained within DIV tags, which relate to a row in a database table.
<?php if($this->userjobdetails != null) : ?>
<?php foreach($this->userjobdetails as $employment) :?>
<div id="employ_<?php echo $this->escape($employment['historyid']);?>">
<table class="employment-table">
<tr>
<td><Strong>
<span dojoType="dijit.InlineEditBox" editor="dijit.form.TextBox" onchange="markEmploymentForUpdate();" id="cmpy_<?php echo $this->escape($employment['historyid']);?>"><?php echo $this->escape($employment['employername']);?></span>
</Strong>
</td>
<td align="left"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" id="roleInput_<?php echo $this->escape($employment['historyid']); ?>" value="<?php echo $this->escape($employment['jobrole']);?>"></td>
<td align="left">
<span dojoType="dijit.InlineEditBox" editor="dijit.form.TextBox" onchange="markEmploymentForUpdate();" id="jtitle_<?php echo $this->escape($employment['historyid']);?>"><?php echo $this->escape($employment['jobtitle']);?></span>
</td>
<td width="15px;">
<input type="hidden" value="<?php echo $this->escape($employment['historyid']);?>" name="employid" id="employid_<?php echo $this->escape($employment['historyid']);?>"/>
<img src="<?php echo $this->baseUrl();?>/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor='pointer';" onclick="removeEmployer('emply_<?php echo $this->escape($employment['historyid']);?>')"/>
</td>
</tr>
</table>
</div>
<?php endforeach;?>
When the user 'saves' the page I want to then using dojo.xhrPost post the data for the elements on the page, so that the database rows are updated.
How would I go about this, having multiple 'rows'??
Thanks
Take a look at dijit.form.Form — the second example shows how to validate a form and do whatever actions you like when user submits it. AFAIK, dijit.form.Form doesn't care how many fields it has, and collects them dynamically.

Categories