MYSQL INSERT循环 - 使用PHP

时间:2012-06-13 19:18:54

标签: php mysql

我假设我正在谈论这是完全错误的时尚,有人可以协助吗?

我想从一张桌子中取出所有带有某个产品编号的行,并在销售时将其放在另一张桌子中。

提前致谢。

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

3 个答案:

答案 0 :(得分: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'

使用此选项语句(第二行和下一行)是原始选择,其中包含您想要指定的值。这样就可以将所有选定的行插入到表格中(顶行)。

答案 1 :(得分: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";

答案 2 :(得分: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'