开发者

Foreach loop with multiple arrays

This is what I want:


f开发者_运维知识库oreach($_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.


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 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/>";
}
?>


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);
}


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.


$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.


Although you already selected an answer, don't forget this piece of script may fail if the POST values are not arrays. You can overcome this with a small piece of code:

$something = is_array($_POST['something']) ? $_POST['something'] : array();
$example = is_array($_POST['example']) ? $_POST['example'] : array();

/* Get all the keys from both arrays
 * If they don't share the keys, none will be lost
 */
$keys = array_merge(array_keys($something),array_keys($example));
$keys = array_unique();

if (count($keys)) {
    $sql = 'INSERT INTO table (row, row2) VALUES ';
    $values = array();

    foreach ($keys as $key) {
        // Single quotes for PHP, we are not expanding variables
        // If the element cannot be converted into a string, don't show the error on screen
        $values[] = '("' . @mysql_real_escape_string($something[$key]) . '","' . @mysql_real_escape_string($example[$key]) . '")';
    }

    $sql .= implode(',', $values);
    mysql_query($sql);
}


Foreach loop with multiple arrays:

foreach($_POST['quantity'] as $key=>$quantity)
{
   $product_no=$_POST['product_id'][$key];
   echo $product_no;
   echo $quantity;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜