Question:

PHP and SQL help: how to insert a loop into a SQL database

by Guest63026  |  earlier

0 LIKES UnLike

I have a for loop that i need to insert into a SQL database. The only problem is that when i try to insert it will only insert the last result and i need to insert all the reslts of the loop. Hope you understood what i'm trying to say, here's an example if it will help you:

$array;

for ($i=0; $i < 5; $i ){

$db_insert = $array[$i];

}

$query = "INSERT INTO something (name) VALUES ('{$db_insert}')";

But it's inserting only $array[4] and i need to insert $array[0] $array[1] $array[2] $array[3] $array[4]

 Tags:

   Report

3 ANSWERS


  1. The first line &quot;$array&quot; is not an array! To instantiate an empty array you say:

    $arr = array();

    And your for loop syntax is wrong. Look up how to use it in the manual. http://uk.php.net/manual/en/control-stru...

    It should look like this:

    for($i=0; $i&lt;5; $i++){

      $arr[] = $i;

    }

    Then you go through the loop to insert it into the db:

    foreach($arr AS $x){

    mysql_query(&quot;INSERT INTO something(name) VALUES(&#039;$x&#039;)&quot;);

    }

    Back to the array thing, if you want to add the numbers 1 to 5 to an array you can do that without a loop by saying: $arr = array(1..5); (I think)


  2. You need to insert your &quot;$query = ...&quot; statement into the for loop.

    Right now it loops til $i = 4, then exits the loop. Insert your query into the loop and it will insert whatever into you table each time.

  3. No Idea, can you help me? 10 points best answer http://answers.yahoo.com/question/index;...

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.