Reputation: 19
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);
}
Upvotes: 1
Views: 1092
Reputation: 2783
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
Upvotes: 0
Reputation: 173572
You should add a unique key for (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.
Upvotes: 2
Reputation: 329
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()';
Upvotes: -1