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.
2
  • 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? Commented Aug 3, 2010 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. Commented Jan 27, 2023 at 0:53

8 Answers 8

10

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}')"); } 
Sign up to request clarification or add additional context in comments.

5 Comments

If $_POSTminimal reproducible example has more values than $_POST[something] then some of the values will be lost
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
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.
hey, that was something else, I read wrong line :D lol thanks very much this works just how I wanted ;)
Just remember to escape your data before inserting it, as others have suggested
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/>"; } ?> 

1 Comment

Why are you posting the same answer on every same post like this one? Just one is enough ...
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); } 

Comments

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.

Comments

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.

4 Comments

You should test if $insertArr does have elements at all.
@premiso: Why not simply adding the condition $cnt > 0 to $cnt == $cnt2?
:) Because its been a long morning!
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). ")";
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); } 

Comments

0

Foreach loop with multiple arrays:

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

Comments

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

2 Comments

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) {
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.