【问题标题】:PHP MySQL INSERT data from another table using the where clause and insert unique values to the same rowsPHP MySQL使用where子句从另一个表插入数据并将唯一值插入相同的行
【发布时间】:2012-10-22 18:17:22
【问题描述】:

我想将数据从一个表插入到另一个表中,其中一个字段等于两个表中的另一个字段。到目前为止,这有效。问题是,我还需要将其他数据插入到第一个表中未包含的相同行中。


//enter rows into database 
foreach($_POST['sku'] as $row=>$sku)
{ 
//this is the data that needs to be added to the table 
$item_sku=$sku;
$image="/$item_sku.jpg";
$small_image="/$item_sku.jpg"; 
$thumbnail="/$item_sku.jpg";

//currently this is what is working to import data from one table to the other
$sql= "INSERT INTO magento_import (sku, description, price) 
       SELECT PR_SKU, PR_Description, PR_UnitPrice
       FROM products 
       WHERE PR_SKU = '$sku'";

//I need something here to add the above variables to the same row where PR_SKU = '$sku'

if (!mysql_query($sql))
{
die('Error: '.mysql_error()); 
}
echo "$row record added";
}

magento_table 上缺失数据的列称为“image”、“small_image”和“thumbnail”。这是一个简单的技巧,可以将旧产品表中的数据放入新产品表中,导出为 CSV,然后在 Magento 中运行配置文件。我不需要担心 SQL 注入。这是我在本地机器上运行的东西。在将产品切换到新的电子商务系统时,我试图避免尽可能多的手动数据输入。感谢您提供的任何帮助。

【问题讨论】:

  • 我说得对吗:附加数据来自外部并且不在旧数据库中的某个位置?您可能需要做一些交互处理和拆分 SQL 语句:通过 sql 获取数据,通过向 php 数组添加值来丰富数据,通过 sql 存储新的数据数组。
  • 请不要在新应用程序中使用mysql_query。它很难正确使用,并且可能导致充满SQL injection points 的危险代码。您的示例是一个要求被利用的巨大责任。使用 PDO 或 mysqli 更安全,更易于正确使用。

标签: php mysql


【解决方案1】:

选择文字值应该符合您的意图:

$sql= "INSERT INTO magento_import (sku, description, price, image, small_image, thumbnail) 
       SELECT PR_SKU, PR_Description, PR_UnitPrice, \"$image\", \"$small_image\", \"$thumbnail\"
       FROM products 
       WHERE PR_SKU = '$sku'";

【讨论】:

  • 选择文字值就像一个魅力。惊人的。非常感谢。
【解决方案2】:

您可以使用另一个更新语句来执行此操作。我怀疑你是否可以用一个查询来做到这一点

foreach($_POST['sku'] as $row=>$sku)
{ 
//this is the data that needs to be added to the table 
$item_sku=$sku;
$image="/$item_sku.jpg";
$small_image="/$item_sku.jpg"; 
$thumbnail="/$item_sku.jpg";

//currently this is what is working to import data from one table to the other
$sql= "INSERT INTO magento_import (sku, description, price) 
SELECT PR_SKU, PR_Description, PR_UnitPrice
FROM products 
WHERE PR_SKU = '$sku'";

//I need something here to add the above variables to the same row where PR_SKU = '$sku'

if (!mysql_query($sql))
{
die('Error: '.mysql_error()); 
}else {

$sql = "UPDATE magento_import SET item='$item',image='$image',small_image='$small_image',thumbnail='$thumbnail' WHERE PR_SKU = '$sku'";
echo "$row record added";
}

}

【讨论】:

    【解决方案3】:

    您可以直接将变量添加到查询中。只要引用它们,它们就会作为简单值起作用。

    $sql= "INSERT INTO magento_import (sku, description, price, x, y, z) 
       SELECT PR_SKU, PR_Description, PR_UnitPrice, '$x' AS x, '$y' AS y, '$z' AS z
       FROM products 
       WHERE PR_SKU = '$sku'";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多