Results 1 to 2 of 2

Thread: How to Combine Multiple Foreach Loops for Updating Database?

  1. #1
    Join Date
    Jan 2003

    Question How to Combine Multiple Foreach Loops for Updating Database?

    I've been using a foreach loop to update ONE field in multiple records of a database from a form. That has worked fine but now I need to update MULTIPLE fields for multiple records.

    Using multiple loops will work -- but I know there's a better way to do this. Recommendations?

    foreach ($recordField1 as $recordID => $recordField1) {
    	$query = "UPDATE database SET recordField1='$recordField1' WHERE recordID='$recordID'";
    	$result = @mysql_query($query);
    foreach ($recordField2 as $recordID => $recordField2) {
    	$query = "UPDATE database SET recordField2='$recordField2' WHERE recordID='$recordID'";
    	$result = @mysql_query($query);
    Thank you for your help!

  2. #2
    Join Date
    Aug 2004
    Are both arrays equivalent in terms of number of elements and having the same exact set of array keys? If so, then you can use the key from one to access the other field from the second array:
    PHP Code:
    foreach($arr1 as $key => $value) {
    $query sprintf(
    "UPDATE some_table SET col1='%s', col2='%s' WHERE col3=%d",
    mysql_real_escape_string($arr2[$key]), // other array

    If the arrays are not equivalent (in terms of size and keys), then we probably need more info to come up with a good solution -- possibly being looking at how you arrived at those two arrays in the first place and if there is a better overall approach.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center