What you need is to create a separate form for each record. Remove <form>
/</form>
tags from the beginning and the end of <table>
and use this code in your last td
:
echo "
...
<td>
<form action='../admin/actions/set-boiler-price.php' method='post'>
£<input type='text' name='price' value='" .$price. "' />
<input type='hidden' name='boilerref' value='" .$boilerref. "' />
<input type='submit' value='update' />
</form>
</td>
</tr>";
With such mark up each form will send it’s own data to your set-boiler-price.php
and updating will work as you expect.
I have a script that displays all the values in a db table. I’d like to be able to update the price value of each row individually on clicking the update button but as it’s in a while loop it’s only updating the final value successfully. I realise this probably requires foreach but I can’t figure where to code it within the loop to send the data from each row to the processing script on the next page. Can anyone help? Thank you!
Display script
<h2>Boiler Prices</h2>
<?php
$sql = "SELECT * FROM emb_prices_boilers ORDER BY id ASC";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
/* Start Form and Table ---------------------------------------------------------*/
echo "<form action='../admin/actions/set-boiler-price.php' method='post'>";
echo "<table id='boiler-prices'>
<tr>
<th>ID</th>
<th>Type</th>
<th>Boiler</th>
<th>Ref</th>
<th>Price</th>
</tr>";
/* Start Loop and Variables --------------------------------------------*/
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$type = $row["type"];
$manufacturer = $row["manufacturer"];
$model = $row["model"];
$boilerref = $row["boilerref"];
$price = $row["price"];
// output data of each row
echo "
<tr>
<td>" .$id. "</td>
<td>" .$type. "</td>
<td>" .$manufacturer. " " .$model. "</td>
<td>" .$boilerref. "</td>
<td>£<input type='text' name='price' value='" .$price. "' /><input type='hidden' name='boilerref' value='" .$boilerref. "' /><input type='submit' value='update' /></td>
</tr>";
}
/* End Loop -------------------------------------------------------*/
echo "</table>";
echo "</form>";
/* End Table and Form -------------------------------------------------------*/
}
else {
echo "0 results";
}
?>
Processing script
<?php
$boilerref = $_POST['boilerref'];
$price = $_POST['price'];
if ($setboilerprice = mysqli_prepare($connection, "UPDATE emb_prices_boilers SET price = ? WHERE boilerref = ?")
) {
/* bind parameters for markers */
mysqli_stmt_bind_param($setboilerprice, "ds", $price, $boilerref );
/* execute query */
mysqli_stmt_execute($setboilerprice);
/* close statement */
mysqli_stmt_close($setboilerprice);
}
else {
echo "error: Failed to write to db";
}
?>