Home > Backend Development > PHP Tutorial > PHP mysql throws an exception when inserting duplicate data. Can the exception be caught?

PHP mysql throws an exception when inserting duplicate data. Can the exception be caught?

WBOY
Release: 2016-07-06 13:52:17
Original
1276 people have browsed it

What I mean is that if it can be inserted, it will return true, if it cannot be inserted, it will return false, but when it cannot be inserted, it will directly display this

PHP mysql throws an exception when inserting duplicate data. Can the exception be caught?

Add my code:

PHP mysql throws an exception when inserting duplicate data. Can the exception be caught?

Reply content:

What I mean is that if it can be inserted, it will return true, if it cannot be inserted, it will return false, but when it cannot be inserted, it will directly display this

PHP mysql throws an exception when inserting duplicate data. Can the exception be caught?

Add my code:

PHP mysql throws an exception when inserting duplicate data. Can the exception be caught?

Of course it is possible.
You can use the following three methods to jump to the page based on your business needs

Ignore: Ignore duplicates.

<code>INSERT IGNORE INTO `table_name` (`email`, `phone`, `user_id`) 
VALUES ('test9@163.com', '99999', '9999');
</code>
Copy after login

Replace: If there are duplicates, delete the old data and add new data

<code>REPLACE INTO `table_name`(`col_name`, ...) VALUES (...);
REPLACE INTO `table_name` (`col_name`, ...) SELECT ...;
REPLACE INTO `table_name` SET `col_name`='value'
</code>
Copy after login

On duplicate key update: If there are duplicates, update

<code>INSERT INTO `table` (`a`, `b`, `c`) VALUES (1, 2, 3), (4, 5, 6) 
ON DUPLICATE KEY UPDATE `c`=VALUES(`a`)+VALUES(`b`);

</code>
Copy after login

Recommended article: MySql method to avoid repeated insertion of records (ignore, Replace, ON DUPLICATE KEY UPDATE)

You can catch this Exception yourself and return true or false

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template