-2

I have the following code that I created to update the database with the data coming from a a php form. $_POST['variables'] are different arrays. the issue I am having is when I echo $updater the field status and the field display values are not in the correct order. for example if I check the checkbox 3. it will return the value enabled on the first line of the results. any suggestions would help thank you

//update data

$priority = $_POST['priority']; // this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
$position = $_POST['position'];
$widgetid = $_POST['widgetid'];
$display = $_POST['display'];

$i = -1;
foreach($priority as $priori)
{
    ++$i;
    $row_enable = $enable[$i];
    $row_height = $height[$i];
    $row_prio   = $priority[$i];
    $positio    = $position[$i];
    $disp       = $display[$i];
    $widgeti    = $widgetid[$i];

    if (isset($enable[$i]))
         $enables ="y";
    else
         $enables ="n";

    if (isset($display[$i]))
         $displ = "y"; 
    else 
         $displ = "n";

    //DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
    $updater = "UPDATE hpoptions SET position='$positio', height='$row_height', status='$enables', display='$displ', priority='$row_prio' WHERE userid='$ud' and widgetid='$widgeti'";

    echo $updater."<br>";

} // ends here 

enter image description here

cppit
  • 4,478
  • 11
  • 43
  • 68

1 Answers1

2

There is no guarantee you will get your arrays in the desired order, unless you force it in the HTML. You probably have something like this:

<input type="text" name="position[]"> 
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w1">
  ...
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w2">
  ...

You need to add an extra dimension to the arrays encoded on the field name. You need an unique id for each field group, and I believe your widgetid is exactly that, right? So you can do:

<input type="text" name="data[w1][position]"> 
<input type="text" name="data[w1][height]"> ...
 ...
<input type="text" name="data[w2][position]"> 
<input type="text" name="data[w2][height]"> ...
 ...

Notice you don't even need a field called widgetid anymore, since the ids will be encoded on every field name. In PHP, you do this to loop through the results:

foreach($_POST['data'] as $widgetid => $data) {
    // Make sure to check if the values won't make your SQL query vulnerable to injection!
    // http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain
    $widgetid = mysql_real_escape_string($widgetid);
    $position = is_numeric($data['position']) ? $data['position'] : 0;
    // ...
    // Build your update query here
}
bfavaretto
  • 71,580
  • 16
  • 111
  • 150