2012-04-23 42 views
0

的想法是插入相同的數據到SQL DB $數量乘以 這意味着如果我有數量= 10 SQL查詢需要插入相同的數據10次 問題是,我總是有一個記錄的詳細 意思是,如果我有數量= 2,我將有3條記錄 如果我有它1,我將有2個記錄等插入多個數據到SQL服務器使用While循環通過PHP

$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連接並在代碼中關閉。

+0

首先,爲什麼要使用「$ quantity」而不是普通變量'$ quantity'? – Eugene 2012-04-23 11:41:11

+0

或多或少的表中有唯一的鍵約束。如果(!mysql_query ... ** inside ** while()**。 – tuxuday 2012-04-23 11:41:41

回答

1

如果您總是有一條記錄太多,那可能意味着您的數量值不正確(?)。

而且,這是不相關的問題,您應該使用while($i<=$quantity)而不是while($i<="$quantity")。你不需要"小號

這第一個塊是確定的:

$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語句再次執行查詢,這意味着你插入一個太多行。刪除整個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++; 
} 
+0

嗨,我相信Quantity是正確的有5條記錄,如果我填寫6條我會有我試圖沒有「和娜事情變化的方式」 – Apocaliptica61 2012-04-23 11:51:32

+0

你說得對,我已經更新了我以前的文章:) – 2012-04-23 11:57:45

+0

如果我移動if(!mysql_query。 while while()裏面的while循環我會得到2更多的記錄,意思是如果我有數量= 2我會得到:5 records.LOL – Apocaliptica61 2012-04-23 12:01:39