Forum Moderators: open

Message Too Old, No Replies

Corrupted results on foreach UPDATE

foreach sizeof input sending arrays

         

salewit

4:14 pm on Sep 10, 2009 (gmt 0)

10+ Year Member



I've got a little database update script that allows me to update inventory quantities. The thing is giving me some trouble so I'm trying to figure out if my code is sound. It's my first attempt at using foreach. Here's the abbreviated code:

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?

whoisgregg

8:54 pm on Nov 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Instead of relying on PHP to keep the $_POST arrays in the right order, just output your primary key data alongside your actual form values:

<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.