简体   繁体   中英

MYSQL INSERT Loop - With PHP

I am assuming I am going about this is the completely wrong fashion, can anyone assist?

I want to take all the rows with a certain product number out of one table and put it in another table when it sells.

Thanks in advance.

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

You just need the one query:

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'

With this the select statement (2nd line and down) is your original select with the values you want specified. This allows all your selected lines to be inserted into your table (top line).

Use only one query INSERT from SELECT:

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";

Use INSERT INTO SELECT.

It is much easier.

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'

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