2012-06-13 133 views
0

我假設我正在做這是完全錯誤的時尚,任何人都可以協助?MYSQL插入循環 - 與PHP

我想從某個表中取出某個產品編號的所有行,並在銷售時將其放入另一個表中。

在此先感謝。

$addinfo1 =""; 
    //Connect to the database through our include 
include_once "connect_to_mysql.php"; 
$sql = mysql_query("SELECT * FROM tm_interested_buyers WHERE fk_product_id='$productid"); 

while($row = mysql_fetch_array($sql)){ 
$interestedbuyersid = $row["pk_interested_buyers_id"]; 
$fkproductid = $row["fk_product_id"]; 
$fkcustomerid = $row["fk_customer_id"]; 

    $addinfo1 .= mysql_query("INSERT INTO tm_int_buyers_complete (fk_interested_buyers_id, fk_product_id, fk_customer_id) VALUES('$interestedbuyersid','$fkproductid','$fkcustomerid')") or die (mysql_error()); 
echo $addinfo1; 
} 

回答

1

你只需要一個查詢:

INSERT INTO tm_int_buyers_complete (fk_interested_buyers_id, fk_product_id, fk_customer_id) 
SELECT pk_interested_buyers_id, fk_product_id, fk_customer_id 
    FROM tm_interested_buyers 
    WHERE fk_product_id='$productid' 

有了這個選擇語句(2號線和下)是你原來跟你想指定的值進行選擇。這樣可以將所有選定的行插入到表格中(頂行)。

0

僅使用一個從SELECT查詢INSERT:

INSERT INTO `tm_int_buyers_complete` (fk_interested_buyers_id, fk_product_id,  fk_customer_id) 
    SELECT fk_interested_buyers_id, fk_product_id, fk_customer_id 
    FROM `tm_interested_buyers` WHERE fk_product_id='$productid"; 
0

使用INSERT INTO SELECT。

這很容易。

INSERT INTO tm_int_buyers_complete (`fk_interested_buyers_id`, `fk_product_id`, 
`fk_customer_id`) SELECT tm_interested_buyers.pk_interested_buyers_id, 
tm_interested_buyers.fk_product_id, tm_interested_buyers.fk_customer_id 
FROM tm_interested_buyers WHERE tm_interested_buyers.fk_product_id='$productid'