php - Avoid Duplicates of Unique Key Within INSERT Query -


i have mysql query looks this:

insert beer(name, type, alcohol_by_volume, description, image_url) values('{$name}', {$type}, '{$alcohol_by_volume}', '{$description}', '{$image_url}')

the problem name unique value, means if ever run duplicates, error this:

error storing beer data: duplicate entry 'hocus pocus' key 2 

is there way ensure sql query not attempt add unique value exists without running select query entire database?

you of course use insert ignore into, this:

insert ignore beer(name, type, alcohol_by_volume, description, image_url) values('{$name}', {$type}, '{$alcohol_by_volume}', '{$description}', '{$image_url}') 

you use on duplicate key well, if don't want add row insert ignore into better choice. on duplicate key better suited if want more specific when there duplicate.

if decide use on duplicate key - avoid using clause on tables multiple unique indexes. if have table multiple unique indexes on duplicate key-clause giving unexpected results (you don't have 100% control what's going happen)

example: - row below updates 1 row (if type 1 , alcohol_by_volume 1 (and both columns unique indexes))

on duplicate key update beer set type=3 type=1 or alcohol_by_volume=1 

to sum up:

on duplicate key work without warnings or errors when there duplicates.

insert ignore into throws warning when there duplicates, besides ignore insert duplicate database.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -