error in PHP & MySQL in a loop

    Date: 07/21/06 (PHP Community)    Keywords: php, mysql, html, database, sql

    The following has been providing a bit of a problem for me over the past few days. I have an initial display page with the HTML form and text fields, however the number of text fields can be controlled by the user. As such they are all placed into an array within the $_POST array, to be retrieved later. I've tried doing this, and this alone works fine. The problem is when I try to loop through them to insert them into the database, for some reason while they will display through echo fine, only the first one will insert into the database, then throw an error. Below is a loose sample of the code.

    The text fields in the HTML file are named as follows : $name[]

    The code in the PHP file is as follows, excluding anything not necessary for the example :




    $conn = db_connect(); // establishes a database connection
    if (!conn)
    {
    echo "database error";
    exit;
    }

    $i = 0;

    while(isset($_POST['name'][$i])){

    $name[] = $_POST['name'][$i];

    $i++;
    }

    $i = 0;

    foreach($name as $name_current){

    echo $name[$i];

    echo $name_current;

    $query = mysql_query("insert into names values ('$other_variable','$other_variable2', '$name_current', '', '', '')");

    $i++;

    if(!$query){
    echo "Database Error";
    exit;
    }else{
    echo "Name added successfully!";
    }
    }



    if anyone can spot something I'm overlooking please let me know, I'm still at a loss for why it will only insert into the query on the first pass through the loop, however if I'm just echoing the values it will work fine.

    Thanks,
    Exeyel

    Source: http://community.livejournal.com/php/472928.html

« J'ai une question. || Dear PHP Community »


antivirus | apache | asp | blogging | browser | bugtracking | cms | crm | css | database | ebay | ecommerce | google | hosting | html | java | jsp | linux | microsoft | mysql | offshore | offshoring | oscommerce | php | postgresql | programming | rss | security | seo | shopping | software | spam | spyware | sql | technology | templates | tracker | virus | web | xml | yahoo | home