4

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.
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • 1
    I don't understand how you are sending the data twice. Could you show some sample output if you put an `echo` in the `foreach`? – KLee1 Aug 03 '10 at 16:36
  • In truth, no one should be writing code like this anymore. A prepared statement should be defined once and executed as many times as needed. – mickmackusa Jan 27 '23 at 00:53

8 Answers8

11

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}')"); 
} 
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • If $_POST[example] has more values than $_POST[something] then some of the values will be lost – Cfreak Aug 03 '10 at 16:45
  • I'm trying to interpret exactly what the OP is asking, based on his comment on sending the data to the database twice. My suspicion is that this is what he means, but is having difficulty explaining – Mark Baker Aug 03 '10 at 16:49
  • 1
    Well, this works, however I get an error: `Warning: Invalid argument supplied for foreach() in example.php on line 63` but I used exactly how you wrote. – Adam Halasz Aug 03 '10 at 17:24
  • hey, that was something else, I read wrong line :D lol thanks very much this works just how I wanted ;) – Adam Halasz Aug 03 '10 at 17:33
  • Just remember to escape your data before inserting it, as others have suggested – Mark Baker Aug 03 '10 at 19:18
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/>";
}
?>
T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • Why are you posting the same answer on every same post like this one? Just one is enough ... – j0k Mar 28 '13 at 10:26
1

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);
}
Andreas
  • 5,305
  • 4
  • 41
  • 60
1
$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.

Jim
  • 18,673
  • 5
  • 49
  • 65
  • 1
    You should test if `$insertArr` does have elements at all. – Gumbo Aug 03 '10 at 16:44
  • @premiso: Why not simply adding the condition `$cnt > 0` to `$cnt == $cnt2`? – Gumbo Aug 03 '10 at 16:51
  • :) Because its been a long morning! – Jim Aug 03 '10 at 16:56
  • Hey, thanks @permiso for your answer, it seems nice however, how should I put other elements in the `mysql_query` other than `something` and `example`, I want before them an `id` too. I was trying something like this but doesn't works :| `$query = "INSERT INTO table (id, something, example) VALUES " ."({$id}, ". implode(", ", $insertArr). ")";` – Adam Halasz Aug 03 '10 at 17:00
1

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.

Cfreak
  • 19,191
  • 6
  • 49
  • 60
1

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);
}
Ast Derek
  • 2,739
  • 1
  • 20
  • 28
0

Foreach loop with multiple arrays:

foreach($_POST['quantity'] as $key=>$quantity)
{
   $product_no=$_POST['product_id'][$key];
   echo $product_no;
   echo $quantity;
}
MikroDel
  • 6,705
  • 7
  • 39
  • 74
0

Yours example dont work in me. I made like this :

if($_POST[add_all]) 
{
$n=0;
foreach($_POST['pieces'] as $checked)    
  {
  if ($checked!=0) 
    {
    $box=$_POST['box'];
    echo $box[$n]."  ".$checked . ' <br>';
    $n++;
    }

  }

<input type="submit" id="coin" name="add_all" value="..Test.."><BR> 
<select name="pieces[]"> 
    <?php for ($x=0;$x<=20;$x++){ echo "<option>$x</option>";} ?>
<input type="checkbox" name="box[]" value="<?php echo"$row_produkt";?>"> 

Robertini
  • 11
  • 3
  • You don't need to manually increment `$n` if `$_POST['pieces']` is an indexed array. Just declare the index variable in the foreach signature. `[...] as $n => $checked) {` – mickmackusa Jan 27 '23 at 01:23
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33713629) – Jeremie Jan 30 '23 at 19:59