【发布时间】:2011-03-30 13:47:48
【问题描述】:
我想根据另一个表中的值更新一个表。如果不存在记录,则作为新记录插入。此代码正确更新,但不会在不存在记录的地方插入。
$results_google = mysql_query("upadate google set
Description = '".mysql_real_escape_string(trim(addslashes(strip_tags($row_first['product_description']))))."',
Manufacturer = '".$row_first['product_vendor']."',
Price = '".$row_first['product_price']."',
Title ='".$row_first['product_title']."'
WHERE product_id = '".mysql_real_escape_string($row_first['product_id'])."';");
if(!$results_google) {
$google = "insert into `google`(`product_id`,`id`,`Description`,`Link`,`Manufacturer`,`Title`,
`Price`,`Shipping_Weight`,`Image_Link`,`Brand`,`inv_id`)
VALUES (
'".mysql_real_escape_string($row_first['product_id'])."',
'".mysql_real_escape_string($row_first['product_id'])."',
'".mysql_real_escape_string(trim(strip_tags(addslashes($row_first['product_description']))))."',
'".mysql_real_escape_string($row_first['product_link'])."',
'".mysql_real_escape_string($row_first['product_vendor'])."',
'".mysql_real_escape_string($row_first['product_title'])."',
'".mysql_real_escape_string($row_first['product_price'])."',
'".mysql_real_escape_string($row_first['weight'])."',
'".mysql_real_escape_string($row_first['image_link'])."',
'".mysql_real_escape_string($row_first['product_vendor'])."',
'$inventory_id')";
mysql_query ($google) or die("google".mysql_error());
}
【问题讨论】:
-
要拥有“如果不存在则插入,如果存在则更新”,请使用
REPLACE或INSERT ON DUPLICATE KEY UPDATE。 -
这与 PHP5 有什么关系?
-
你在第 1 行写了“更新”,你能正确缩进你的代码吗?
-
并且不要从字符串构建 SQL,您的代码不可读,甚至可能不安全。
-
@Konerak:在 99% 的情况下,
INSERT ON DUPLICATE KEY UPDATE是首选,因为REPLACE会将表数据分段(因为它实际上执行删除和插入),并且可能默认所有字段t 插入。