Reputation: 141
hope you fine and well,
i have the following form:
<form class="hidden-print" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tr>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * from persons";
$i=0;
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo'<input type="hidden" name="id[]" value="' . $row['id'] . ' ">';
echo '<td>'. $row['Name'] . '</td>';
echo'<input type="hidden" name="name[]" value="' . $row['Name'] . ' ">';
$i++;
}
Database::disconnect();
?>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Send" >
</form>
let me explain what happening here, my form is PHP_SELF so i post the data to the same page, i created a table inside the form which contains ID's and Names, i loop through the selected data and each row in the table will contain id and name of person, as you see, i defined the inputs name and id as arrays eg. name[] and id[] , and i have a submit button at the end of the form will post the arrays id[] and name[].
now what i want is to put an submit input in each row ! so when i click the submit button it will post just the id and the name of the person in this row !
is this possible ?!
regards.
Upvotes: 0
Views: 1317
Reputation: 23948
You are already using associative array in names e.g. name[]
Use counters:
name[<?php echo $i;?>]
And add submit buttons with the same
<input type="submit" name="submit[<?php echo $i;?>]"/>
In PHP, loop over $_POST
.
And check index of submit button using foreach
loop.
Use the same index for name
, id
, etc.
Hope it helps.
Answer updated with code:
<form class="hidden-print" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tr>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * from persons";
$i=0;
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo'<input type="hidden" name="id['.$row['id'].'" value="' . $row['id'] . ' ">';
echo '<td>'. $row['Name'] . '</td>';
echo'<input type="hidden" name="name['.$row['id'].'" value="' . $row['Name'] . ' ">';
?>
<td>
<input class="btn btn-primary" type="submit" value="Send" name="send<?php echo $rowp['id'];?>" >
</td>
</tr>
<?php
++$i;
}
Database::disconnect();
?>
</tr>
</table>
</form>
<?php
if (! empty($_POST['send'])) {
foreach ($_POST['send'] as $key => $posted) {
$id = isset($_POST['id'][$key]) ? $_POST['id'][$key] : '';
$name = isset($_POST['name'][$key]) ? $_POST['name'][$key] : '';
// Do your SQL here.
}
}
?>
Note: HTML mark ups are used as it is, please correct it as per your needs.
Upvotes: 1