检查MySQL中的记录并创建(如果不存在)

时间:2015-06-24 19:57:19

标签: php mysql

当我点击立即购买按钮时,我正在检查我的mysql数据库表中是否存在记录(产品ID),如果他们没有创建另一个,如果他们这样做,只需更新现有的。 / p>

它创建了第一个记录正常,当我再次点击它而不创建另一个记录时它甚至更新,但是当我点击另一个产品时它会创建另一个记录并且它永远不会更新以下记录。

换句话说,它只是更新第一个产品ID,并为其余产品创建新记录。

这是我的表enter image description here

的图像
function add_to_cart(){

global $connection;

$ip = getIp();



if(isset($_GET['add'])) {

$product_id = $_GET['id'];
$product_price = get_item_price($product_id);


$query = "SELECT * FROM cart WHERE ip_address = '{$ip}' ";
$check_query = query($query);
confirm($check_query);
$row = fetch_array($check_query);
$db_product_id = $row['product_id'];

if(mysqli_num_rows($check_query) === 0 || $product_id != $db_product_id)  {

$query = "INSERT INTO cart(product_id,ip_address,quantity,price_sum) VALUES('{$product_id}', '{$ip}' ,1, '{$product_price}')";

$send_query_cart = query($query);
confirm($send_query_cart);
redirect("index.php");

} else {

$query = "UPDATE cart SET quantity = quantity + 1, price_sum = price_sum + '{$product_price}' WHERE product_id = '{$product_id}' ";
$update_records = query($query);
confirm($update_records);
redirect("index.php");



}




}








}

1 个答案:

答案 0 :(得分:0)

可能最好的解决方案是在(我假设)UNIQUEproduct_id上创建ip_address约束。

ALTER TABLE `cart` ADD UNIQUE `unique_index`(`ip_address`, `product_id`);

然后,我根本不会将商品的价格保存在购物车中。可以在商品表中查找商品的价格。订单完成后,您可以保存单个商品的价格,因为它可能会更改,但是当它在购物车中时,您需要最近的价格。

完成后,您的查询可以简化为

$query = "INSERT INTO cart(product_id,ip_address,quantity)
              VALUES ('{$product_id}', '{$ip}', 1) 
          ON DUPLICATE KEY UPDATE 
              quantity = quantity+1";

,您甚至不必检查它 - 查询将处理更新或自动插入。

此外,我不会依赖ip_address来识别用户 - 如果有人在乘坐汽车时在手机上购物,则很容易改变。同一路由器上的两个人可能看起来与您的网站具有相同的IP地址。我会在会话中或在安全的cookie中保存一些内容并使用它来识别它们。

要获得总数,您可以执行以下操作:

$totals = "SELECT cart.product_id, cart.quantity * products.price as product_price_total
           FROM cart
           LEFT JOIN products USING(products.id = cart.product_id)
           WHERE ip_address = '{$ip}'";