使用While循环通过PHP将多个数据插入SQL服务器

时间:2012-04-23 11:37:00

标签: php mysql sql

这个想法是将相同的数据插入SQL DB $ quantity次 这意味着如果我有数量= 10,SQL查询需要插入相同的数据10次 问题是我总是有一个记录 意思是如果我有数量= 2我会有3条记录 如果我有1,我将有2个记录,所以

$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());
}

我有sql连接并关闭代码。

1 个答案:

答案 0 :(得分:1)

如果您的记录总是太多,那可能意味着您的数量值不正确(?)。

此外,这与您的问题无关,您应该使用while($i<=$quantity)代替while($i<="$quantity")。您不需要" s

第一个块是好的:

$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语句执行您的查询AGAIN,这意味着您插入了太多行。删除整个if语句将解决“插入太多行”问题。

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

或者,将while循环更改为:。

$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++;
}