首页 > 解决方案 > 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');
}

标签: phpduplicatesmariadbsql-insert

解决方案


为了防止插入重复,您可以使用下一个代码:

$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');
}

PHP PDO 在线测试

此外,此代码在准备好的语句中使用参数来防止 SQL 注入


推荐阅读