可能重复:
如果它不存在则创建一个mysql记录,否则更新它
我创建了一些 PHP,它从 CSV 获取数据并更新数据库表以匹配 CSV 的数据。
我的下一个任务是,根据唯一列 (sku) 检查记录是否存在。如果确实存在,则根据更改更新数据库表。否则,如果该 SKU 列不匹配,请执行 INSERT。
我目前拥有的代码正在运行,但是我遇到的问题是,如果创建了一个新项目,它似乎会通过现有记录运行更新。
我的代码可以在Pastebin上找到
或者也在这里...
<?php
$con = mysql_connect("localhost", "root", "");
if(!$con)
{
die('Could not connect' . mysql_error());
}
mysql_select_db("db_lemonstand", $con);
class csvIterator extends LimitIterator
{
public function __construct($path)
{
$csv = new SplFileObject($path);
$csv->setFlags(SplFileObject::READ_CSV);
parent::__construct($csv, 1);
}
}
foreach (new csvIterator('data/catalogue.csv') as $entry) {
$name = $entry[23];
/* Replace Strings To Make URL Name */
$search_array = array(" ", "/", "+");
$replace_array = array("-");
$url_name = strtolower($name);
$url_name = str_replace($search_array, $replace_array, $url_name);
$long_desc = $entry[9];
$short_desc = $entry[23];
$manufacturer = $entry[11];
$price = $entry[15];
$sku = $entry[2];
$weight = $entry[29];
$width = $entry[30];
$height = $entry[5];
$enabled = '1';
$created_at = date('Y-m-d H:i:s');
$product_type_id = '1';
$tax_class_id = '1';
echo '<pre>';
print_r($entry);
echo '</pre>';
// Check see if products' SLU already exists or not
$product_exists = "SELECT sku FROM shop_products WHERE sku = '$sku'";
$result = mysql_query($product_exists, $con);
$exists = mysql_num_rows($result);
if($exists == 0 )
{
$insert = "INSERT INTO shop_products (name, description, short_description, url_name, price, sku, weight, width, height, enabled, created_at, tax_class_id, product_type_id) VALUES ('$name', '$long_desc', '$short_desc', '$url_name', '$price', '$sku', '$weight', '$width', '$height', '$enabled', '$created_at', '$tax_class_id', '$product_type_id')";
$insert_data = mysql_query($insert, $con);
}
else
{
$update = "UPDATE shop_products SET name = '$name', description = '$long_desc', short_description = '$short_desc', url_name = '$url_name', price = '$price', sku = '$sku', weight = '$weight', height = '$height', enabled = '$enabled', created_at = '$created_at', tax_class_id = '$tax_class_id', product_type_id = '$product_type_id'";
$update_data = mysql_query($update, $con);
if (!mysql_query($update,$con))
{
die('Error: ' . mysql_error());
}
}
}