从一个表导入数据并将其插入另一个表

时间:2014-04-23 05:40:09

标签: php mysql

我有两张表product_myobproducts。我想要做的是在点击导入按钮到表product_myob时从products导入产品。表products已包含一些产品

我尝试执行以下查询但该表未更新。请帮我解释一下代码。

INSERT INTO products(myob_id, myob_displayID, Name)
  SELECT UID,displayID,itemName 
  FROM product_myob 
  WHERE UID NOT IN (SELECT myob_id from products);

2 个答案:

答案 0 :(得分:0)

这是您可以使用的示例代码。使用 MySQLi ,因为 MySQL 已弃用。

<?php

/* ESTABLISH CONNECTION AND CHANGE THE NECESSARY HOST, USERNAME, PASSWORD AND DATABASE */

$connection=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");

if(mysqli_connect_errno()){

echo "Error".mysqli_connect_error();
}

$result=mysqli_query($connection,"SELECT * FROM product_myob");
while($row=mysqli_fetch_array($result)){

$myobid=mysqli_real_escape_string($con,$row['UID']);
$myobdisplayid=mysqli_real_escape_string($con,$row['displayID']);
$name=mysqli_real_escape_string($con,$row['itemName']);

/* CHECK IF DATA IS ALREADY IN THE products TABLE */

   $result2=mysqli_query($connection,"SELECT * FROM products WHERE myob_id='$myobid' AND myob_displayID='$myobdisplayid' AND Name='$name'");

   if(mysqli_num_rows($result2)==0){

   mysqli_query($connection,"INSERT INTO products (myob_id, myob_displayID, Name) VALUES ('$myobid','$myobdisplayid','$name')");

   } /* END OF IF MYSQLI_NUM_ROWS($RESULT2) IS 0 */

   else {
   echo "Data has already been inserted before.<br>";
   }

} /* END OF WHILE LOOP RESULT */

?>

答案 1 :(得分:0)

似乎您的产品表上有一个独特的检查,如果是这种情况,您正在插入一些重复数据,那么您可以通过以下查询忽略重复值,即使您不需要检查产品表中的UID因为此查询会自动忽略它。其他明智地阐述了你的问题:

INSERT ignore INTO products(myob_id, myob_displayID, Name)
  (SELECT UID,displayID,itemName 
  FROM product_myob);