Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2004
    Posts
    19

    Unanswered: how to loop an insert query into MySQL

    I just cant make the loop to work.

    it only insert the first row from the query.

    This is the code:

    for ($i=0; $i < $totalRows_central; $i++)

    {
    $name=mysql_result($central,$i,"name");
    $query="insert into test values('','".$name."')";
    mysql_query($query);
    }


    Does any body knows how to insert all the query _result into the table ?

  2. #2
    Join Date
    Jul 2004
    Location
    Dundee, Scotland
    Posts
    107
    The code you have there is mixed up so I can see why it's not working. Can you explain more about what you are doing... what is the source of the data you are trying to insert into the test table? Does each loop build a single row which is to be inserted into the table, or does each loop add to a single insert statement which is to be executed after the loop completes?

    This might help you:

    <run a query>

    $field_count = mysql_num_fields($result);

    for($i = 0; $i < $field_count; $i++) {
    echo mysql_field_name($result,$i);
    echo(",");
    }

    while($row = mysql_fetch_array($result)) {
    for($i = 0; $i < $field_count; $i++) {
    echo($row[$i].",");
    }
    echo("\n");
    }

  3. #3
    Join Date
    Jan 2004
    Location
    India
    Posts
    168
    First find out why ur query is not working what is wrong in that. So put a die function like:
    for ($i=0; $i < $totalRows_central; $i++)

    {
    $name=mysql_result($central,$i,"name");
    $query="insert into test values('','".$name."')";
    mysql_query($query) or die(mysql_error());
    }
    This will give the error that mysql gives.

    Hope by this we can figure a better method to solve your problem.

    Regards
    Rajesh

  4. #4
    Join Date
    Dec 2003
    Location
    Houston, TX
    Posts
    21
    You could add the variables to an array in one loop and then in the 2nd loop array_pop() them off. In the 2nd loop is were I had my mysql_query statement. I used this once when I was affecting multiple rows at a time that all had a similar name.

    Try adding this to your code.
    ...
    $query="insert into test values('','".$name."')";
    //mysql_query($query) or die(mysql_error());
    echo "<p> QUERY: $query </p>";
    ...

    That should help you debug it before you are ready to actually affect the database. I would use phpmyadmin too create a dupilcate database or table you want to work on and then use the output of your query statement from this web page to test it.
    I do not fear computers. I fear the lack of them.
    -Isaac Asimov (1920 - 1992)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •