Is it possible to handle MySQL errors in php? In particular, is it possible to find out what the error is based on the result of a failed request. Specifically, it came to mind when a record with the existing name established by PRIMARY KEY is thrown into the database. Is it possible to catch the error and display the correct message to the user? Or do you need to check the request first?
3 answers
Learning The PDOException class
- there is not only a PDOException, again a person about PDO may not have heard. - kemerov4anin
- one@ kemerov4anin I took on the mission to teach newbies to normal coding. therefore, there are no other handlers for MYSQL. reads the article, will see that it is conveniently interested, will switch to PDO and in the world will be a few lines less than the Hindu code. - FLK
- @FLK thanks for the effort. I am very grateful for your indifference) inspired)) I will surely read, since it is convenient and I will try to reduce the number of my Ida code lines. - Ray
- @ Andrei Baksh for such comments and worth living! Thanks) - FLK
- @FLK, about life is a pleasant humor) I have recently taken upon myself the same mission as you. Somewhere deep in my heart, I am happy that I am not the only one on the same resource. All govnododer we do not eradicate, of course. But let's at least let them not produce. Thanks to everyone who adheres to my point of view and to you, @FLK, separately) - Vitaly Kustov
|
In php, there is the Exception class, which, with the help of the try-catch construct, can and should be used. Examples here .
- try-catch is clear. but how, for example, when executing a request to add an entry, with an already existing key of the type PRIMARY KEY, do I know which error the function returned? try-catch only allows you to find a site where this is possible, i.e. in which function. - Ray
- and who prevents you from throwing mysql_error ()? - kemerov4anin
|
Of course you can! The most simple error detection in the request:
$res = mysql_query("SELECT 1"); echo($res);
You can also use the mysql_error()
function:
mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("nonexistentdb"); echo mysql_errno() . ": " . mysql_error(). "\n"; mysql_select_db("kossu"); mysql_query("SELECT * FROM nonexistenttable"); echo mysql_errno() . ": " . mysql_error() . "\n";
In fact, errors can be handled in completely different ways. Even, for example, get a list of table fields for analyzing the structure:
$fields = mysql_list_fields("datebase", "qmex_users", $resourse_connection); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { echo mysql_field_name($fields, $i) . "\n"; }
- Not. You did not understand me) Through a preliminary request, it is clear that you can check, etc. Is it possible to get, for example, an error code and knowing how to process it? - Ray
|