简体   繁体   中英

PHP MySQL Insert Query that won't insert if already exists

I've been doing some research and haven't found anything that I've been able to make work, unfortunately, and I think that stems from not understanding the MySQL construct in the examples I've been looking at.

What I'm trying to do is run an insert query, and do a check on values in 3 specific columns to ensure they don't exist, then insert, else do nothing.

My Table is pretty basic: id(int11), user(varchar(45)), label(varchar(255)), agent(varchar(255)), empid(varchar(10)).

My id is my Primary, with Auto increment, and here is my code I currently have that works on inserting, but doesn't have the handling in place for duplicates:

$i = 0;
foreach ($agents as $ag){
    $sql = mysql_query("INSERT INTO `pms_users` 
    (`id`,`user`,`label`,`agent`,`empid`)
     VALUES 
    (NULL, '$user','$group','$labels[$i]','$ag')");
    $i ++;
}

The three columns I need to check against are the $user, $group, and $ag.

Add a unique index for (user, label, empid) . Then the database won't allow you to create duplicates.

ALTER TABLE pms_users
ADD UNIQUE INDEX (user, label, empid);

If you can only have one row per combination of user, label and agent, you should define them as a unique constraint:

ALTER TABLE pms_users ADD CONSTRAINT pms_users_unq UNIQUE (`user`, `label`, `agent`);

And then let the database do the heavy lifting with an insert-ignore statement:

INSERT IGNORE INTO `pms_users`
(`user`, `label`, `agent`, `empid`)
VALUES ('some_user', 'some_label', 'some_agent', 123)

You can try insert on duplicate key update query.. It checks duplicate keys. If they exist MySQL do update query if not exist MySQL doing insert query. Sure in your database you should declare unique keys. Here is MySQL documentation for this case https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM