views:

91

answers:

5

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.
+1  A: 

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
+1  A: 
$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.

Brad F Jacobs
You should test if `$insertArr` does have elements at all.
Gumbo
Yea, good call. Added in an if statement for that.
Brad F Jacobs
@premiso: Why not simply adding the condition `$cnt > 0` to `$cnt == $cnt2`?
Gumbo
:) Because its been a long morning!
Brad F Jacobs
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). ")";`
CIRK
@premiso sry :S :D
CIRK
+1  A: 

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

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
A: 

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