-3

How can I insert this array to database using loop?

Array ( 
[0] => 1 
[1] => 0 
[2] => 0 
) 

I try like this way:

$chimp= Array ( 
    [0] => 1 
    [1] => 0 
    [2] => 0 
    ) 

foreach ($reponse as  $value) {
        $values= mysql_real_escape_string($value);
                foreach ($chimp as $valuech  ) {
                    $valuesch= mysql_real_escape_string($valuech);

     $query = mysql_query("INSERT INTO reponses (nom_reponse,id_question,id_categorie,correct2) VALUES ('$values','$last_id','$categorie','$valuesch')") 
        or die(mysql_error());


                        }
                        }

I need the steps to insert $reponse and $chimp data in each row?

fpj
  • 315
  • 1
  • 14
4code
  • 41
  • 2
  • 10
  • What happens with the current code you have? – chris85 Jun 12 '15 at 01:22
  • For starters you don't show the $response array... Suggestion use mysqli instead of [deprecated mysql](http://php.net/manual/en/changelog.mysql.php) , then use [mysqli prepare](http://php.net/manual/en/mysqli.prepare.php) – lukesUbuntu Jun 12 '15 at 01:30
  • i'm able to insert the first foreach for reponse ; but i could not insert the second value for this array . the question is how can insert the value 0 0 1 to database thanks for replay – 4code Jun 12 '15 at 01:33

1 Answers1

0

You are looping incorrectly currently your insert will execute 9 times. Whereas you want it to execute three times.

Example of current execution:

http://sandbox.onlinephpfunctions.com/code/ef1821fb0fe7dcc96a3f48e9ec8453 8cdfb5db62

You need to use the key to pair up both array values, you could do that with a for loop or by using the key in the foreach, http://php.net/manual/en/control-structures.foreach.php.

<?php
$reponse = array (1, 0 ,0);
$chimp = array (1, 0, 0);
foreach ($reponse as $key => $value) {
    $values= mysql_real_escape_string($value);
    $valuesch= mysql_real_escape_string($chimp[$key]);
    $query = mysql_query("INSERT INTO reponses (nom_reponse,id_question,id_categorie,correct2) VALUES ('$values','$last_id','$categorie','$valuesch')") 
        or die(mysql_error());
    }
}

I don't know where $last_id or $categorie are coming from so make sure those values are correct.

Here's how the loop will process now. http://sandbox.onlinephpfunctions.com/code/1b8af87984c348a326a64e2d453ddcdf17b65b5f

I didn't touch the SQL, looks right to me presuming your column names are correct.

chris85
  • 23,846
  • 7
  • 34
  • 51
  • thanks a lot sir for replay this is a good example that help me to understand and it work for me :) – 4code Jun 12 '15 at 02:32