lundi 13 avril 2015

Multiple update buttons on single form

Please forgive me for the terribly structured code. I'm attempting to update different customers on each line with an individual submit button. The delete function works great. I'm trying to pass the ID of the row when the submit button is clicked for each row. However, I'm getting the ID for the last row, no matter which row I click. I've attached a screenshot as an example. Any help is appreciated!


Screenshot of output



<form action="" method="post">
<table class="table table-striped table-bordered table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
<th>Product</th>
<th>Firmware Version</th>
<th>Purchase Date</th>
<th>Delete</th>
</tr>
</thead>
<?php
$pdo = new PDO("mysql:host=localhost;dbname=project", $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$query = $pdo->prepare("select * from customers");
$query->execute();
while($customers = $query->fetch()){
$ID = $customers['ID'];
echo '<tr><td><input type="text" name="name" value="';
echo $customers['name'];
echo '"></td>';
echo "<td>" . $customers['email'] . "</td>";
echo "<td>" . $customers['phone'] . "</td>";
echo "<td>" . $customers['address'] . "</td>";
echo "<td>" . $customers['product'] . "</td>";
echo "<td>" . $customers['firmware'] . "</td>";
echo "<td>" . $customers['purchase_date'] . "</td>";
echo '<td align="center"><input type="hidden" name="id" value="';
echo $ID;
echo '"><input type="submit" name="delete" value="X"> </td></tr>';
echo '<tr><td colspan="8"><input type="hidden" name="id_update" value="';
echo $ID;
echo '"><input type="submit" name="update" value="Update">';
echo $ID . '<--This is the ID for each row';
echo '</td></tr>';
}

// Delete customer
if(isset($_POST['delete'])) {

try{
$ID = $_POST['id'];
$query = $pdo->prepare("delete from customers where ID = :ID");
$query->bindParam(':ID', $ID);
$query->execute(array(
':ID' => $ID
));
echo "Customer successfully deleted.";
echo '<META http-equiv="refresh" content="1;URL=view_edit.php">';
}catch(PDOException $e){
echo "Failed to delete the MySQL database table ... :".$e->getMessage();
} //end of try
} //end of isset delete


// Edit customer
if(isset($_POST['update'])) {
echo "Update " . $_POST['id_update'] . '<-- This is the result of clicking update for each row';
} //end of isset update

?>
</table>
</form>

Aucun commentaire:

Enregistrer un commentaire