Is it possible to handle MySQL errors in php?

Is it possible to handle MySQL errors in php? In particular, is it possible to find out what the error is from the result of the Failed Request. Specifically, this came to mind when a record is thrown into the database with an already existing full name set by PRIMARY KEY. Is it possible to “catch” the error and display the correct message to the user? Or do you need to check with a query beforehand?

Answer 1, authority 100%

Learning The PDOException class

Answer 2, authority 50%

In php, there is a class Exception, which, using the try-catch construct, can and should be used. Examples here.

Answer 3

Of course you can! The easiest way to detect an error in a request is:

$res = mysql_query("SELECT 1");

You can also use the function mysql_error():

mysql_connect("localhost", "mysql_user", "mysql_password");
echo mysql_errno() . ": " . mysql_error(). "\n";
mysql_query("SELECT * FROM nonexistenttable");
echo mysql_errno() . ": " . mysql_error() . "\n";

In fact, you can handle errors in completely different ways. Even, for example, to get a list of table fields for structure analysis:

$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";

Leave a reply

Please enter your comment!
Please enter your name here