如何在插入数据库之前检查重复项?
How to check for duplicates before inserting into database?
所以我做了一个将照片添加到收藏夹的功能,我该怎么做才不会一直添加相同的图像?
我的代码:
function addToFavorites($fileName)
{
global $conn;
$email = $_SESSION['email'];
$imageId = $_GET["id"];
$sql = "insert into favorites set UserEmail='".mysqli_real_escape_string($conn, $email)."', ImageID=".$imageId;
$result = mysqli_query($conn, $sql);
如有帮助将不胜感激!
您让数据库完成工作!只需在 table:
上定义唯一约束或索引
alter table favorites add constraint unq_favorites_useremail_imageid
unique (useremail, imageid);
有了这个约束,如果您尝试插入重复项,数据库将 return 出错。
如果想避免错误,可以使用on duplicate key update
:
insert into favorites (UserEmail, ImageId)
values (?, ?)
on duplicate key update ImageId = values(ImageId);
关于此的一些说明:
?
是一个 参数占位符 。学习使用参数而不是修改查询字符串中的值。
- 这不使用
set
。那是一个 MySQL 扩展。在这种情况下没有任何优势;您不妨使用标准语法。
on duplicate key
是一个空操作,但它可以防止代码在出现重复时 return 出错。
如果您想避免像 Gordon Linof 所说的错误,您可以执行查询:
SELECT FROM favorites WHERE UserEmail='".mysqli_real_escape_string($conn, $email)."' AND ImageID=".$imageId
如果有returns0条记录执行插入一条。这是最安全的方法。
所以我做了一个将照片添加到收藏夹的功能,我该怎么做才不会一直添加相同的图像?
我的代码:
function addToFavorites($fileName)
{
global $conn;
$email = $_SESSION['email'];
$imageId = $_GET["id"];
$sql = "insert into favorites set UserEmail='".mysqli_real_escape_string($conn, $email)."', ImageID=".$imageId;
$result = mysqli_query($conn, $sql);
如有帮助将不胜感激!
您让数据库完成工作!只需在 table:
上定义唯一约束或索引alter table favorites add constraint unq_favorites_useremail_imageid
unique (useremail, imageid);
有了这个约束,如果您尝试插入重复项,数据库将 return 出错。
如果想避免错误,可以使用on duplicate key update
:
insert into favorites (UserEmail, ImageId)
values (?, ?)
on duplicate key update ImageId = values(ImageId);
关于此的一些说明:
?
是一个 参数占位符 。学习使用参数而不是修改查询字符串中的值。- 这不使用
set
。那是一个 MySQL 扩展。在这种情况下没有任何优势;您不妨使用标准语法。 on duplicate key
是一个空操作,但它可以防止代码在出现重复时 return 出错。
如果您想避免像 Gordon Linof 所说的错误,您可以执行查询:
SELECT FROM favorites WHERE UserEmail='".mysqli_real_escape_string($conn, $email)."' AND ImageID=".$imageId
如果有returns0条记录执行插入一条。这是最安全的方法。