Yes, in your original output loop each line will have to have the id (primary key) as well as the name. Then you can loop through all the names, get the id field for the corresponding name field, and update the database. Probably didn’t help that my example above never incremented the field name counter suffix, but you probably noticed that, also I didn’t pass through the value of ‘count’ to do the second loop.
if ($num > 0) {
print '<form method="post" action="whatever.php">';
$cnt = 0;
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$fldname = "name" . $cnt;
$idname = "id" . $cnt;
print '<p>'.$row['name'].'</p>
<input type="hidden" name="' . $idname . '" value="' . $row['name_id'] .'>
<input type="text" name="' . $fldname . '" size="" maxlength="" value="';
echo $row['name']; // this is the name from the query
print'" /> </p>';
print'<p>'.$row['price'].'</p>';
$cnt +=1;
}
print '<p><input type="hidden" name="count" value = "' . $cnt . '"><input type="submit"></p></form>';
}
so the above should give you a table that has the name, price and a hidden var for each field that contains the id, assuming your id is in $row[‘name_id’] in the table, something like:
<form method="post" action="whatever.php">
<p>Jet Black</p>
<input type="hidden" name="id0" value="1001">
<input type="text" name="name0" value="Jet Black">
</p>
<p>15.75</p>
<p>Dave Greenfield</p>
<input type="hidden" name="id1" value="1002">
<input type="text" name="name1" value="Dave Greenfield">
</p>
<p>18.95</p>
<input type="hidden" name="count" value="2">
<input type="submit">
</form>
As you see, it’s created fields with different names for each name entry (which it wouldn’t have in my first example code as I didn’t increment $cnt). Then to store the updated data, in your whatever.php:
$process = 0;
$cnt = $_POST['count'];
while ($process < $cnt) {
$q = "update tablename set name = " .$_POST['name' . $process] . " where name_id = " . $_POST['id' . $process];
// execute the query, not sure of the mysqli syntax
$process += 1;
}
So it will run around that loop twice, for values 0 and 1 in the example, retrieve name0 and id0, update the table, then retrieve name1 and id1, and update the table, then end the loop. As I mentioned, it would probably be nice to add a feature to only update if the name has changed.
Also obviously some sanitising of data is needed, I haven’t bothered with that in the example. Looking again at your first post, you seem to loop around a query but then try to display the ‘name’ field from $_POST, wouldn’t that be from $row instead? I have assumed so in this post though I didn’t notice it first time around.