如何将重复条目停止到数据库中

时间:2022-08-11 00:15:23

Hi there i am trying to insert an array of information into fields in a database through the selection of checkboxes i have that sorted and inserting fine but i am able to insert duplicates which is no good i am using the following to insert the items

您好我在尝试通过选择复选框将信息数组插入数据库中的字段我已经排序和插入正常但我能够插入重复项,这是不好的我使用以下插入项目

    $list = $_POST['sub'];

    // for each loop to insert each value into the database with the selected users informtion
    foreach ($list as  $value)  {

        // The query to run
        $listQuery='INSERT INTO tbl_list (`userId`, `subId`) VALUES (\'' . $id . '\', \'' . $value . '\')';


        // Run the query
        $objects->query($listQuery);


    }

4 个解决方案

#1


2  

You should add a unique key for (userId, subId):

您应该为(userId,subId)添加唯一键:

ALTER TABLE tbl_list ADD UNIQUE(`userId`, `subId`)

Then, you should use either INSERT IGNORE or REPLACE INTO to avoid errors during insert.

然后,您应该使用INSERT IGNORE或REPLACE INTO来避免插入期间的错误。

#2


0  

You can use Insert Ignore instead of Insert in mysql query

您可以在mysql查询中使用Insert Ignore而不是Insert

#3


0  

For stop duplicate entries into database you have do this thing.follow step by step

要将重复的条目停止到数据库中,您可以执行此操作。请按步骤进行操作

> 1.set a unique key on the table

after Complete create unique key you have to decide what you want to do when there's a duplicate

> 2. ignore it

> 3.Overwrite the previously entered record

> Update some counter

#4


-1  

You need to do two things first make your userId primary key and then try this query
$listQuery='INSERT INTO tbl_list (userId, subId) VALUES (\'' . $id . '\', \'' . $value . '\') on duplicate key update userId = LAST_INSERT_ID()';

你需要先做两件事,先做你的userId主键,然后尝试这个查询$ listQuery ='INSERT INTO tbl_list(userId,subId)VALUES(\''。$ id。'\',\''。$ value。' \')重复密钥更新userId = LAST_INSERT_ID()';

#1


2  

You should add a unique key for (userId, subId):

您应该为(userId,subId)添加唯一键:

ALTER TABLE tbl_list ADD UNIQUE(`userId`, `subId`)

Then, you should use either INSERT IGNORE or REPLACE INTO to avoid errors during insert.

然后,您应该使用INSERT IGNORE或REPLACE INTO来避免插入期间的错误。

#2


0  

You can use Insert Ignore instead of Insert in mysql query

您可以在mysql查询中使用Insert Ignore而不是Insert

#3


0  

For stop duplicate entries into database you have do this thing.follow step by step

要将重复的条目停止到数据库中,您可以执行此操作。请按步骤进行操作

> 1.set a unique key on the table

after Complete create unique key you have to decide what you want to do when there's a duplicate

> 2. ignore it

> 3.Overwrite the previously entered record

> Update some counter

#4


-1  

You need to do two things first make your userId primary key and then try this query
$listQuery='INSERT INTO tbl_list (userId, subId) VALUES (\'' . $id . '\', \'' . $value . '\') on duplicate key update userId = LAST_INSERT_ID()';

你需要先做两件事,先做你的userId主键,然后尝试这个查询$ listQuery ='INSERT INTO tbl_list(userId,subId)VALUES(\''。$ id。'\',\''。$ value。' \')重复密钥更新userId = LAST_INSERT_ID()';