简体   繁体   中英

Inserting multiple data to SQL server using While loop via PHP

the idea is to insert the same data to SQL DB $quantity times it mean that if i have quantity = 10 the SQL query need to insert the same data 10 times the problem is that always i have one record more mean if i have the quantity=2 i will have 3 records if I have it to 1 i will have 2 record and so

$i=1; 
while ($i<="$quantity")   
{
  $sql="INSERT INTO arivage (ID_Ship, Date_ariv, Date_achat, prov_id, Sph, cyl, Prod_type, Pord_color)  
       VALUES ('', '$date', '$date1', '$prov_id', '$sph', '$cyl', '$Prod_type', '$Prod_color')";
  mysql_query($sql);      
  $i++;
}
if (!mysql_query($sql,$con))
{
  die('Error: ' . mysql_error());
}

i have the sql connection and closing in the code too.

If you always have one record too many, that probably means your quantity value is not correct (?).

Also, this is not related to your problem, you should use while($i<=$quantity) instead of while($i<="$quantity") . You do not need the " s

This first block is ok:

$i=1; 
while ($i<="$quantity")   
{
    $sql="INSERT INTO arivage (ID_Ship, Date_ariv, Date_achat, prov_id, Sph, cyl, Prod_type, Pord_color)  
        VALUES ('', '$date', '$date1', '$prov_id', '$sph', '$cyl', '$Prod_type', '$Prod_color')";
    mysql_query($sql);      
    $i++;
}

The next if statement executes your query AGAIN, meaning you insert one too many rows. Removing the entire if statement would solve your "one too many rows is inserted" problem.

if (!mysql_query($sql,$con))
{
    die('Error: ' . mysql_error());
}

Alternatively, change your while loop to:.

$i=1; 
while ($i<="$quantity")   
{
    $sql="INSERT INTO arivage (ID_Ship, Date_ariv, Date_achat, prov_id, Sph, cyl, Prod_type, Pord_color)  
    VALUES ('', '$date', '$date1', '$prov_id', '$sph', '$cyl', '$Prod_type', '$Prod_color')";
    if(!mysql_query($sql, $con)) {
        die('Error: ' . mysql_error());
    }
    $i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM