php - How do I prevent my 'insert' query from inserting duplicates in mariadb?
问题描述
I wrote this code to collect post info via a form and insert it into my database and it's definitely doing its job. The problem is that each time the code is executed, it inserts multiple duplicates of the information gotten from the form. Any idea how to stop this from happening? Here's a code snippet for context:
$query= $connect->prepare("insert into posts (title,date,author,content,image) values('$title','$date','$author','$content','$fileNameNew');");
$query->execute();
if($query->execute()){
echo('POST UPLOADED SUCESSFULLY');
$query->close();
}else{
echo('POST UPLOADED HAS FAILED');
}
解决方案
为了防止插入重复,您可以使用下一个代码:
$query = $connect->prepare("insert into posts (title,date,author,content,image) values(?, ?, ?, ?, ?);");
if($query->execute([$title,$date,$author,$content,$fileNameNew])){
echo('POST UPLOADED SUCESSFULLY');
}else{
echo('POST UPLOADED HAS FAILED');
}
此外,此代码在准备好的语句中使用参数来防止 SQL 注入
推荐阅读
- javascript - 我正在尝试使用两个按钮计算按钮点击的总数并将其显示在文本区域中
- javascript - 将对象的值数字转换为字符串无法正常工作
- python - 填充缺失值的数据框(熊猫)
- postgresql - 让 LIKE 搜索使用 citext 表达式的索引
- excel - 删除 A 列或 B 列中的单元格为空的行
- go - 使用给定数据创建一个 JSON 数据作为 map[string] 接口
- azure - 如何基于孤盘创建快照
- python - 如何分隔列表中的文本?
- powershell - 属性未出现在 Get-Member cmdlet 中,并且在放入 . 符号
- python - 矩阵形式 NxN 邻接矩阵