如何获取MySQL错误参数?

In case of a MySQL error, such as duplicate entry, I want to get the name of the field that caused the problem. I'm doing it like this:

$err = $mysqli->error;
$errno = $mysqli->errno;
...
if ($errno == 1062)
{
    $begin = strpos($err, "' for key '") + 11;
    $end = strlen($err) - 1;
    $arg = substr($err, $begin, $end - $begin);
}

and so $arg stores the name. This doesn't feel like a super solid way to do it though since, as far as I know, there is no guarantee that the format of the error stays the same from version to version and database to database.

Is there a more direct way to get the name of that field?

You would do a nested CASE statement as follows. The result will return the fields with a duplicate entry. If more than 1 duplicate entry it will respond for each one.

   SELECT PD.column_name1, PD.column_name2, PD.column_name3 FROM table_name WHERE PD.column_name1 = value1, PD.column_name2 = value2, PD.column_name3 = value3 AS PD (SELECT CASE
      WHEN PD.column_name1 = value1 THEN "column_name1" 
      WHEN PD.column_name2 = value2 THEN "column_name2" 
      WHEN PD.column_name3 = value3 THEN "column_name3")