Looping through an array of checkbox - php

I have a form with rows which are populated from a table. Each row has a "checkbox" which the user can check or not.
When the form is submitted I want to be able to read which checkbox have been selected and insert the result in to a data table.
My code so far
FORM:
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table
<?php do { ?>
<tr>
<td>input type="text" name="InspectRoomNo" value="<?php print $row_InspectItems['AuditItemNo']; ?>"></td>
<td>php echo $row_InspectItems['AuditItem']; ?>td>
<td>input name="check[]" type="checkbox" ></td>
</tr>
<?php } while ($row_InspectItems = mysql_fetch_assoc($InspectItems)); ?>
<input type="submit" value="Insert record">
</table>
The insert: fetchs $Items from table
while($row = mysql_fetch_assoc($Items))
{
$array[] = $row['AuditItem'];
}
foreach($array as $id) {
$AuditItemID = mysql_real_escape_string($id);
if(isset($_POST['check'])){
$Checked = mysql_real_escape_string($_POST['check'][$row]);
}
}
The problem I am having is the returned values for all the checkbox is true, even if a checkbox was not selected.
Can anyone help me sort this issue.
Many thanks.

Do it like this:
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
echo $check;
}
}

You should put the item id inside the checkbox name:
<td><input name="check[<?= $row_InspectItems['AuditItem']; ?>]" type="checkbox" /></td>
Then, you can simply iterate over it:
foreach ($_POST['check'] as $id => $value) {
// do stuff with your database
}
I'm assuming than whomever runs this script is trusted, because it would be easy to forge the list of ids; make sure the current user has permissions to update those records.

What is happening, is that only selected checkboxes get sent to the server, so you will see that your $_POST['check'] array (this is an array!) is smaller than the number of items you have displayed on the screen.
You should add your ID's so that you know what checkboxes got checked and adapt your php processing code to handle an array instead of a single value.
You are also overwriting your InspectRoomNo every row, so you should use an array there as well.
The form side would look something like:
<td><input type="text" name="InspectRoomNo[<?php echo row_InspectItems['AuditItemNo']; ?>]" value="<?php print row_InspectItems['AuditItemNo']; ?>"></td>
<td><?php echo $row_InspectItems['AuditItem']; ?></td>
<td><input name="check[<?php echo row_InspectItems['AuditItemNo']; ?>]" type="checkbox" ></td>

Related

How to select checkbox in database mysqli table in PHP

**How to select checkbox in database mysqli
what should i write in checkbox value
please kindly help
i also implode function which convert array to string
did not find values for checkbox values to print. .....
Also check the output on PICTURE...
**
OUTPUT PIC
<?php
while($fetch=mysqli_fetch_array($select))
{
?>
<tr>
<td><?php echo $fetch["tableno"]?></td>
<td><?php echo $fetch["customerid"]?></td>
<td><?php echo $fetch["item"]?></td>
<td><?php echo $fetch["money"]?></td>
<td><button>Delete</button></td>
<td><a href="update.php?tableno=<?php echo $fetch["tableno"]; ?>"/><button>Update</button></td>
<td><form method="POST">
<input type="checkbox" name="chk[]" value="???">
<input type="submit" name="sub1" value="Button for Checkbox">
</td> </form>
</tr>
<?php
}?>
</table>
<p style="font-size:30px">The Customer has TO Selected these Items from Menu List
and therefore submitted to<br> Kitchener to Make the Food and
then waiter will serve the Food to Customer.</p>
</body>
</html>
<?php
if(isset($_POST['sub1']))
{
$chk=implode(',', $_POST['chk']);
echo "<br>Customer has selected the following checkbox Item to be Prepared and Eat the Food:<br/>";
echo "<br/>".$chk."<br><br/><br/><br/><br/>";
}
?>
Try this:
In you form, method to insert multiple checkboxes
<form method="POST" action="test2.php">
<input type="checkbox" name="chk[]" value="InputText1">InputText1<br>
<input type="checkbox" name="chk[]" value="InputText2">InputText2<br>
<input type="submit" name="sub1">
</form>
if(isset($_POST['sub1'])) // check the submitted form and print the values
{
echo "You selected the following checkbox:<br/>";
foreach ($_POST['chk'] as $value) {
echo $value."<br>";
}
One method is the value of a checkbox can be concatenated with all data and after submitting, check for selected check boxes with for each loop and print all the selected rows. Like below
<input type="checkbox" name="chk[]" value="<?php echo "<td>".$fetch["tableno"]."</td><td>".$fetch["customerid"]."</td><td>".$fetch["item"]."</td><td>".$fetch["money"]."</td>"; ?>">
And after posting use this :
if(isset($_POST['sub1'])) // check the submitted form and print the values
{
echo "Below Customers have placed orders:<br/>";
echo "<table>";
foreach ($_POST['chk'] as $value) {
echo "<tr>".$value."</tr>";
}
echo "</table>";
}

PHP get the table data row input value using loop

I am having a issue in getting the correct value from the table.
The issue I encountered:
When I choose the second checkbox the and input a quantity, it is Undefined offset: 0
But the value of the checkbox is working and correct.
What I am expecting is when I choose the second or other checkbox (exclude first checkbox), I should get the value of that input field.
HTML
<?php foreach($results as $row) { ?>
<tr>
<td><input type="checkbox" name="products[]" value="<?php echo $row->items_id; ?>"></td>
<td><?php echo $row->item_name; ?></td>
<td><input type="number" name="quantity[]" class="form-control"></td>
</tr>
<?php } ?>
<input type="submit" name="process" class="btn btn-primary" value="Process">
PHP
$quantity = $_POST['quantity'];
$products = $_POST['products'];
$count_selected = count($products);
for($i=0; $i< $count_selected; $i++){
var_dump($quantity[$i]); exit;
}
The problem with checkboxes is that an unchecked one submits no value so your $_POST['products'] and $_POST['quantity'] arrays may have different lengths.
I'd combine using a hidden input with specific array indexes.
For example
<?php foreach($results as $row) : ?>
<tr>
<td>
<input type="hidden" name="products[<?= $row->items_id ?>]" value="0">
<input type="checkbox" name="products[<?= $row->items_id ?>]" value="1">
</td>
<td><?= htmlspecialchars($row->item_name) ?></td>
<td><input type="number" name="quantity[<?= $row->items_id ?>]" class="form-control"></td>
</tr>
<?php endforeach ?>
Then the arrays will have the same indexes and you can iterate them with a foreach
foreach ($_POST['products'] as $itemId => $checked) {
// $checked represents the state of the checkbox
// you can access quantity via $_POST['quantity'][$itemId]
}
You could even create a nice filtered array of quantities via
$selections = $_POST['products'];
$quantities = array_filter($_POST['quantity', function($itemId) use ($selections) {
return $selections[$itemId];
}, ARRAY_FILTER_USE_KEY);
first, define array variable.
$products =array( );
$quantity=array( );
other wise every thing seems fine.

Submitting a specific row of a form which is generated by a loop

This is the code for the admin panel of a certain site. Appointments asked by customers will be shown in this page. The admin will be able to change the appointments based on availability.
<?php
while($row = mysqli_fetch_assoc($result)){
?>
<form action="adminEdit.php" method="POST">
<tr>
<td><input type="text" id="name" value="<?php echo $row['Name'];?>"></input></td>
<td><input type="text" id="address" value="<?php echo $row['Address'];?>"></input></td>
<td><input type="text" id="phone" value="<?php echo $row['Phone'];?>"></input></td>
<td><input type="text" id="license" value="<?php echo $row['Car_License_No'];?>"></input></td>
<td><input type="text" id="engine" value="<?php echo $row['Car_Engine_No'];?>"></input></td>
<td><input type="text" id="date" value="<?php echo $row['Date'];?>"></input></td>
<td><input type="text" id="mechanic" value="<?php echo $row['Mechanic'];?>"></input></td>
<td><input type="submit" name="submit" value="Change"/></td>
</tr>
</form>
<?php
}
?>
Here, each row of data has a corresponding button which will be used for changing or modifying the records of that particular row. Once the admin changes a specific appointment it should get updated in database.
My problem is, all the rows are getting generated by a while loop. Now how can I access a specific row when the change button of that specific row has been clicked ? As the rows are getting generated by a loop, I wont be able to access them bynameoridbecause all of them will have the samenameandid`.
Searched for relevant questions but none of them matched with my scenario. It will be of great help getting an answer. Thanks in advance.
Personally I'd be inclined to take the output from being in the loop for better control over the data and resolving the issue. You're also creating a new form on each loop.
Just loop the DB and create a new variable, then use that variable to output the data in the form.
Example code to show the basic idea, not tested or stating it's complete etc:
while ($row = mysqli_fetch_assoc($result)) {
$someNewVar[$row['id']] = $row;
// The 'id' index would be from DB which identifies individual rows
}
?>
<form action="adminEdit.php" method="POST">
<?php
foreach ($someNewVar as $index => $value) {
?>
<tr>
<td>
<input
type="text"
id="<?php echo $index;?>"
value="<?php echo $value['Name'];?>">
</input>
</td>
<td>
<input
type="submit"
name="submit"
value="Change"/>
</td>
</tr>
<?php
}
?>
</form>
Then you'd need to have the row ID passed from clicking the submit button.
On a side note, this whole approach could be tidied up, and data should be obtained in one file separate to where you output it.
Then in the file which obtains the data you can set the array to something which is also identified in the output file to manage if no data was obtained.
ie
getData.php
while ($row = mysqli_fetch_assoc($result)) {
$dataFromDb[$row['id']] = $row;
}
$someNewVar = !empty($dataFromDb) ? $dataFromDb : false;
showData.php
if ($someNewVar) {
// do the loop and form
} else {
echo 'sorry no data found';
}

Trying to update dates in database with dynamically created forms

So i've created an administration page that creates X-number of forms based on how many users we have in our database, each of which have a submit button next to them to submit changes to the dates we have in our DBs. My problem is that when I want to get the value of what gets posted I can't extract exactly what I need from what gets posted. It gets saved into an array called and when I print_r the array I get exactly what I want, which is:
[1] => "whatever date they typed in"
(obviously the 1 changes depending on which item they changed the date of)
I need be able to query my datebase by:
UPDATE users SET subdate="whatever they typed in" WHERE id="the array reference number"
I know exactly what I need to do, I'm just not as familiar with SQL as i'd like to be, so any help would be greatly appreciated. Thanks in advance.
Code for reference:
<div class="form-section grid12" id="changedates">
<h1>Change Dates</h1>
<?php
$query = mysql_query("SELECT * FROM users WHERE admin='y'");
?>
<table>
<?php
while($row = mysql_fetch_assoc($query)) {
?>
<tr>
<td>
<h5><?php echo $row['displayname'];?></h5>
</td>
<td>
<form action="" method="POST">
<input type="text" name="subdate[<? echo $row['id'] ?>]" value="<?php echo $row['submissiondate'];?>">
<input type="text" name="nextupdate[<? echo $row['id'] ?>]" value="<?php echo $row['nextupdate'];?>">
</td>
<td>
<input type="submit" value="Set Date" name="setdate">
</form>
</td>
<?php
}
?>
</table>
</div>
You could use foreach...
foreach ($_POST[nextupdate] as $rowId => $time)
{
// do db update
}
Edit: Just realised you have more than one input per form.
Why not name each input with an array name:
<input type="text" name="form_data[<?= $row_id ?>][subdate]">
<input type="text" name="form_data[<?= $row_id ?>][nextupdate]">
In PHP:
foreach ($_POST[form_data] as $rowId => $values)
{
$subdate = $values[subdate];
$nextupdate = $values[nextupdate];
// do SQL stuff
}

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.

Categories