2012-10-22 80 views
0

我希望將數據從一個表插入另一個表中,其中一個字段等於另一個表中的數據。這到目前爲止有效。問題是,我還需要將其他數據插入到第一個表中未包含的相同行中。PHP MySQL使用where子句從另一個表中插入數據並向同一行插入唯一值


//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丟失的數據的列被稱爲 '圖像', 'small_image' 和 '縮略圖'。將舊數據表中的數據放入新的產品表中,以CSV格式導出,以及在Magento中運行配置文件,這很簡單。我不需要擔心SQL注入。這是我從本地機器上運行的東西。我試圖在將產品切換到新的電子商務系統時避免儘可能多的手動數據輸入。謝謝你提供的所有幫助。

+1

我能幫到你嗎:額外的數據來自外部,並不駐留在舊數據庫的某處?你可能必須做一些內部處理和分解SQL語句:通過sql獲取數據,通過向php數組添加值來豐富數據,通過sql存儲新的數據數組。 – matthias

+0

請不要在新的應用程序中使用'mysql_query'。正確使用非常困難,並且可能會導致充滿[SQL注入點]的惡意代碼(http://bobby-tables.com/php)。你的例子是一個**巨大的**負債,要求被剝削。使用PDO或'mysqli'相當安全,並且更易於正確使用。 – tadman

回答

2

選擇文字值應該做你想要什麼:

$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'"; 
+0

選擇文字值就像魅力一樣工作。真棒。非常感謝你。 – JRJP

0

您可以使用另一個更新語句來執行此操作。我懷疑,如果你能做到這一點有一個單一的查詢

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

} 
0

您只需直接添加變量到查詢。只要他們被引用,他們將作爲簡單的價值觀來工作。

$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'"; 
相關問題