www.webdeveloper.com
Results 1 to 2 of 2

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

  1. #1
    Join Date
    Jan 2003
    Posts
    226

    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?

    Code:
    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
    Location
    Ankh-Morpork
    Posts
    19,616
    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($value),
          
    mysql_real_escape_string($arr2[$key]), // other array
          
    $key
       
    );

    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.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

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



Recent Articles