我正在使用最近开始学习的 PHP 和 MySQL 创建一个基本的电子商务网站。我有一个具体问题。每当我添加两个同名产品时,就会将重复产品添加到数据库中。有没有办法避免相同的情况,而是增加数量的数字。
else{
$product_image = addslashes(file_get_contents($_FILES['fileField']['tmp_name']));
include_once("../scripts/connect.php");
$sql = mysql_query("INSERT IGNORE INTO products(name, brand, category, sizes, description, price, quantity, product_image, date_added) VALUES('$product_name','$product_brand','$product_category','$product_sizes','$product_description','$product_price','$product_quantity','$product_image', now())");
$id = mysql_insert_id();
$msg = "Success!";
}
最佳答案
不推荐在生产中使用上述代码,因为它容易受到 sql 注入(inject)攻击。尝试使用 UNIQUE
来自数据库或使用的约束:
alter table products add unique index(name, brand, category, sizes, description, price, quantity, product_image, date_added);
小贴士:
- mysql_函数已弃用并已从 php 7 中删除。使用 mysqli_函数或 PDO 代替。
- 使用准备好的语句来避免 sql 注入(inject)。
关于php - 避免电子商务网站中的产品重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35391019/