how to avoid duplicate records insertion in php my

2019-04-11 10:03发布

How do I avoid duplicate records insertion in PHP MYSQLi? this my script :

$nama=$_POST['nama'];
$member=$_POST['member'];
$peserta=$_POST['peserta'];
$tour=$_POST['tour'];

mysqli_query($conn,"insert into gathering (nama, member, peserta, tour) values ('$nama', '$member', '$peserta', '$tour')");

header('location:index.php');

标签: php mysql mysqli
4条回答
Bombasti
2楼-- · 2019-04-11 10:43

Below code will help you inserting unique data:

$result = mysqli_query($conn, "SELECT nama, member, peserta, tour FROM gathering where nama = '$nama' and member = '$member' and peserta='$peserta' and tour='$tour'")
$total = mysqli_num_rows($result);

if($total==0)
{
    mysqli_query($conn,"insert into gathering (nama, member, peserta, tour) 
values ('$nama', '$member', '$peserta', '$tour')");
} 
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-11 10:56

1.You can alter table with Unique constraint :

ALTER TABLE mytbl ADD UNIQUE (columnName);
  1. get record from table before insert record and check whether record is already exist or not.

    $dupesql = "SELECT * FROM gathering where (nama = '$nama' )";
    $duperaw = mysql_query($dupesql);
    if (mysql_num_rows($duberaw) > 0) {
       show error msg;
    }else{
       mysqli_query($conn,"insert into gathering (nama, member, peserta, tour) values ('$nama', '$member', '$peserta', '$tour')");
    }
    
查看更多
你好瞎i
4楼-- · 2019-04-11 11:02

tambahkan kolom dengan primary key

ALTER TABLE gathering ADD COLUMN `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
查看更多
【Aperson】
5楼-- · 2019-04-11 11:03

first check if the row exists and then insert

$res= mysqli_query($conn,"select * from gathering where nama='$nama' and member='$member' and peserta='$peserta' and tour='$tour'");

if(mysqli_num_rows($res)=0)
{
mysqli_query($conn,"insert into gathering (nama, member, peserta, tour) values ('$nama', '$member', '$peserta', '$tour')");
}
else
{
echo "record already exists";
}
查看更多
登录 后发表回答