Home > Database > Mysql Tutorial > How to Update MySQL Data if it Exists or Insert if Not?

How to Update MySQL Data if it Exists or Insert if Not?

Susan Sarandon
Release: 2024-11-13 07:16:02
Original
997 people have browsed it

How to Update MySQL Data if it Exists or Insert if Not?

PHP/MySQL: Update if Exist or Insert if Not

You seek to update a MySQL table if specific fields exist, or insert if they do not. This scenario involves joining three tables: set_colors, school_art, and baseimage.

To achieve your desired outcome, consider the following code:

This updated code employs the INSERT ... ON DUPLICATE KEY UPDATE statement in MySQL. It performs the following actions:

  • Inserts new rows if the (school_art_id, baseimage_id) pair is not found.
  • Updates existing rows if the (school_art_id, baseimage_id) pair already exists.
  • In case of an update, only the sub_folder and layer columns are updated to the values provided in the VALUES clause.

The above is the detailed content of How to Update MySQL Data if it Exists or Insert if Not?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template