Forum Moderators: open
HTML Form part values read in from database.
<p>Green Widget <input type='text' name='onhand[]' value='3' size=2><input type='hidden' name='primarykey[]' value='938'></p>
<p>Doodad <input type='text' name='onhand[]' value='22' size=2><input type='hidden' name='primarykey[]' value='131'></p>
<p>Blue Widget <input type='text' name='onhand[]' value='0' size=2><input type='hidden' name='primarykey[]'
value='655'></p>
PHP Processing
include("openmysqldb.php");
for ($i=0; $i< sizeof($_POST['primarykey']) ;$i++) {
$command = "UPDATE inventory set onhand = '" . $_POST['onhand'][$i] . "' WHERE primarykey = '" . $_POST['primarykey'][$i] . "' LIMIT 1;";
$resultID = mysql_query($command,$linkID);
}
Here's the problem. When I just submit the form above without making any changes, no problems. But if I change one field for example, if I change the Doodad from 22 to say 8 and submit, the database gets corrupted fairly randomly from what I can tell and Doodad will then become something like 3 and Blue Widget might become 22. I can't pinpoint the pattern exactly. Is the code above the proper way to deal with this?
<p>Green Widget <input type='text' name='onhand_938' value='3' size=2></p>
<p>Doodad <input type='text' name='onhand_131' value='22' size=2></p>
<p>Blue Widget <input type='text' name='onhand_655' value='0' size=2></p>
Then you can loop through your $_POST array and get the correct primary keys for the UPDATE:
foreach ($_POST as $key => $value) {
if(preg_match('/^onhand_[0-9]+$/',$key)){
$primarykey = substr($key, 7); // grab everything after onhand_
$command = "UPDATE inventory set onhand = '" . mysql_real_escape_string($value) . "' WHERE primarykey = '" . mysql_real_escape_string($primarykey) . "' LIMIT 1;";
// echo $command; // for debugging
$resultID = mysql_query($command,$linkID);
}
}
Ideally, you'd do some additional validation on the input as well.