I have a user creation screen that takes various user details along with first name and mobile number. I have a corresponding USER table in which the First Name and the Mob
Here's a PHP version of eggyal's answer, using MySQLi.
// Error: 1062 SQLSTATE: 23000 (ER_DUP_ENTRY) Message: Duplicate entry '%s' for key %d
// Error: 1586 SQLSTATE: 23000 (ER_DUP_ENTRY_WITH_KEY_NAME) Message: Duplicate entry '%s' for key '%s'
if($mysqli->errno === 1062 || $mysqli->errno === 1586)
{
if(preg_match("/Duplicate entry '(.*)' for key '(.*)'/", $mysqli->error, $matchArray) === 1)
{
$duplicatedValue = $matchArray[1];
$uniqueKeyName = $matchArray[2];
if(!($stmt = $mysqli->prepare('SELECT COLUMN_NAME'
. ' FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE'
. ' WHERE CONSTRAINT_SCHEMA = ?'
. ' AND CONSTRAINT_NAME = ?')))
{
die; // Error? Check $mysqli->errno and $mysqli->error;
}
$schemaName = // Name of the schema (string).
if(!$stmt->bind_param('ss', $schemaName, $uniqueKeyName))
{
die; // Error? Check $mysqli->errno and $mysqli->error;
}
if(!$stmt->execute())
{
die; // Error? Check $mysqli->errno and $mysqli->error;
}
$res = $stmt->get_result();
if(!$res)
{
die; // Error? Check $mysqli->errno and $mysqli->error;
}
$row = $res->fetch_assoc();
if($row === null)
{
die; // No results?
}
$columnName = $row['COLUMN_NAME'];
}
}