A
A
Alexey Konovalov2021-07-30 12:47:48
MySQL
Alexey Konovalov, 2021-07-30 12:47:48

Can Mysql error code be trusted?

Hello! If the posts table has a connection with the users table through the user_id => id field and an insertion occurs into the posts table where the user_id field contains the value 3, but there is no such id in the users table. Then Mysql returns an error with the number 1452.
Can I trust this number and be sure that it will not change in the same situation later and make a check

if($db->errno === 1452){
   throw new Exception("Такого пользователя не существует");
}


Or, before inserting, you need to create a query to check the existence of such a record in the link table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-07-30
@Alk90

Server Error Message Reference

Error number: 1452; Symbol: ER_NO_REFERENCED_ROW_2; SQLSTATE: 23000
Message: Cannot add or update a child row: a foreign key constraint fails (%s)
InnoDB reports this error when you try to add a row but there is no parent row, and a foreign key constraint fails. Add the parent row first.

This error is always generated by the event of a failed check of the referential integrity constraint. So you can safely trust the reason.
Or, before inserting, you need to create a query to check the existence of such a record in the link table?

But ask yourself a question - where will the very value of user_id = 3 that you are going to insert come from? I don't see any other way to get this value other than querying the parent table. And if the desired value is returned from it, then the record from which this value is taken is quite obviously in the table.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question