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

3
  • What happens with the current code you have? Commented Jun 12, 2015 at 1:22
  • For starters you don't show the $response array... Suggestion use mysqli instead of deprecated mysql , then use mysqli prepare Commented Jun 12, 2015 at 1: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 Commented Jun 12, 2015 at 1:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot sir for replay this is a good example that help me to understand and it work for me :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.