简体   繁体   中英

save data in form of arrays to mysql database using a foreach loop

I have a form that submits multiple values using php. code is below:

    echo "<form action='?ud=".$ud."' method='post'>Name: <input type='text' name='fname' />";
$resultw = mysql_query("SELECT * FROM options where userid='$ud' ORDER BY priority ASC");

while($row = mysql_fetch_array($resultw))
  {  
  echo "
 <input type='hidden' name='widgetid[]' value='".$row['widgetid']."' />
  <span id='".$row['widgetid']."' style='color:white;font-size:13px;'>".$row['items'] .    "</span><br></div><div style='' class='portlet_content'>
   Enabled <input title='Enabled/Disabled' type='checkbox' value='enable[]' name='enable[]' ".$checked." id='checkbox".$row['id']."' />  
   Height <input title='set height' name='height[]' value='".$row['height']."' type='text' name='textfield' id='textfield".$row['id']."' />
 ";
  } 

  echo '<input type="submit" /></form>';?> 

as you can see its a loop thats get the values from db and echoes a form. I made it as simple as possible it has more input boxes but i removed them and removed the styling to make it simpler to read. when I hit Submit I would like to be able to have all those values updated to the database through a loop. I tried foreach and struggled. any suggestions

First of all, your code has a security bug in that you are directly putting a variable into a SQL query. That allows for SQL injection. Instead, you should put the variable $ud through mysql_real_escape_string before inserting into the query or, significantly better, use MySQLi/PDO and prepared statements.

Have you checked that the form is correctly echoed onto the page? View the source (or use Firefox and Firebug) to double check that it has been properly inserted.

Then you will need to have a code block that is initiated when it receives a POST request. That code will get an array back for each of your variables eg

 $widget_ids = $_POST['widgetid']; #this will be an array
 $enable = $_POST['enable'];
 $height = $_POST['height'];

You can do this for each of your POSTed variables and then just loop round the widget ids doing an update query for each one eg

$i = -1;
foreach($widget_ids as $widget_id) {
      $row_enable = $enable[++$i];
      $row_height = $height[$i];
      //DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
}

Just to be pedantic, your HTML is also a bit messy and incorrect. For a form I would use label elements for each label and don't use br's for new lines. You also have a div with no beginning and then a div with no ending.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM