Foreach loop with multiple arrays

14,766

Solution 1

Do you mean something like:

foreach($_POST['something'] as $key => $something) { 
    $example = $_POST['example'][$key];
    $query = mysql_query("INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')"); 
} 

Solution 2

SOLUTION FOR MULTIPLE Arrays

TRY -

1)

<?php
$ZZ = array('a', 'b', 'c', 'd');
$KK = array('1', '2', '3', '4');

foreach($ZZ as $index => $value) {
    echo $ZZ[$index].$KK[$index];
    echo "<br/>";
}
?>

or 2)

<?php
$ZZ = array('a', 'b', 'c', 'd');
$KK = array('1', '2', '3', '4');

for ($index = 0 ; $index < count($ZZ); $index ++) {
  echo $ZZ[$index] . $KK[$index];
  echo "<br/>";
}
?>

Solution 3

Your solution does not seem to send the data twice. Unless if records with the same values appear as a result of issuing your queries. This might mean that you should process your data before constructing your queries.

One solution could be:

$sql = array();

foreach($_POST['something'] as $something){
    foreach($_POST['example'] as $example){
    $sql[] = "INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')";
}
}

foreach($sql as $query){
  mysql_query($query);
}

Solution 4

$cnt = count($_POST['something']);
$cnt2 = count($_POST['example']);

if ($cnt > 0 && $cnt == $cnt2) {
    $insertArr = array();
    for ($i=0; $i<$cnt; $i++) {
        $insertArr[] = "('" . mysql_real_escape_string($_POST['something'][$i]) . "', '" . mysql_real_escape_string($_POST['example'][$i]) . "')";
    }

    $query = "INSERT INTO table (column, column2) VALUES " . implode(", ", $insertArr);
    mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}

Here is another method. This one uses extended inserts, so should be more efficient and quicker, and utilizes mysql_real_escape_string for security reasons. The count check is to just make sure that both fields have the same count, if not then I take this is a mishap. If they are allowed to have a different number of fields, you can simply use the isset() function to check to make sure they contain a value.

EDIT

This is assuming of course, that you do not want 'something' to iterate over all the 'example' values and be assigned to each one. If you want that well it is a bit of a change up.

Added an insert array test, if there are no elements no need to update. Thanks Gumbo for that.

Solution 5

I think the best way would be as a single loop to build a query. This should work even if your arrays are not the same length:

$size1 = count($_POST['something']);
$size2 = count($_POST['example']);
if( $size1 >= $size2 ) {
     $size = $size1;
} else {
     $size = $size2;
}

$sql = "INSERT INTO table (row, row2) VALUES";
$values = array();
for( $i=0; $i<$size; $i++ ) {
    $values[] = "('" . mysql_real_escape_string($_POST['something'][$i]) . "','" . mysql_real_escape_string($_POST['example'][$i]) . "')";
}

$sql .= implode(",", $values);

mysql_query($sql);

Also more secure because it escapes your input. This would also be even easier using placeholders with PDO.

Share:
14,766
Adam Halasz
Author by

Adam Halasz

Hi, I made 37 open source node.js projects with +147 million downloads. Created the backend system for Hungary's biggest humor network serving 4.5 million unique monthly visitors with a server cost less than $200/month. Successfully failed with several startups before I turned 20. Making money with tech since I'm 15. Wrote my first HTML page when I was 11. Hacked our first PC when I was 4. Lived in 7 countries in the last 4 years. aimform.com - My company adamhalasz.com - My personal website diet.js - Tiny, fast and modular node.js web framework

Updated on June 11, 2022

Comments

  • Adam Halasz
    Adam Halasz almost 2 years

    This is what I want:


    foreach($_POST['something'] as $something){
        foreach($_POST['example'] as $example){
            $query = mysql_query("INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')");
        }
    
    }
    

    $_POST['something'] and $_POST['example'] are arrays from an input with

    name="something[]" and name="example[]".

    The problem:


    In this way I will send the data twice to database. So I need a solution where I can loop trough 2 arrays without seding the data twice.

    EDIT

    • The two array will always have the same size
    • In the mysql_query I will have other elements not just row, row2, and those will be static without any array.