30

I have a PHP form that enters data into my MySQL database. My primary key is one of the user-entered values. When the user enters a value that already exists in the table, the MySQL error "Duplicate entry 'entered value' for key 1" is returned. Instead of that error, I would like to alert the user that they need to enter a different value. Just an echoed message or something.

How to turn a specific MySQL error into a PHP message?

7 Answers 7

54

To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:

mysqli_query('INSERT INTO ...');
if (mysqli_errno() == 1062) {
    print 'no way!';
}

A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (1062) to a constant (e.g. MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)

5
  • Yeah, I just found that too :D I plugged it in and it worked perfectly. Thanks jensgram, just the solution I was looking for! Jun 30, 2010 at 7:13
  • @jensgram: +1 thanks for very useful answer & tip. I'm just adding this link for those using PDO: php.net/manual/en/pdo.errorcode.php Sep 22, 2011 at 8:09
  • 1
    For OOP it's $mysqli->errno.
    – i336_
    Jan 17, 2017 at 11:22
  • to find out error number: echo mysqli_errno($link); //where link is your database connection. Jul 26, 2020 at 14:49
  • Why do you spend a while paragraph on instructing the reader to use constants, instead of just (or at least in addition to) applying it to your code snippet?
    – m7913d
    Dec 25, 2021 at 11:46
5

You can check the return value from mysql_query when you do the insert.

$result = mysql_query("INSERT INTO mytable VALUES ('dupe')");

if (!$result) {
    echo "Enter a different value";
} else {
    echo "Save successful.";
}
4
  • Aha, i've seen this before, and this definitely looks right. thanks nickf! Jun 30, 2010 at 6:29
  • Actually, is there any way to check if it's the specific error? Jun 30, 2010 at 6:33
  • Yep - mysql_errno() will return the error code of the last error. Off the top of my head, I don't know what that code is, but you could just check for that inside the (!$result) branch.
    – nickf
    Jun 30, 2010 at 7:57
  • The OOP equivalent of mysql_errno() is $mysqli->errno.
    – i336_
    Jan 17, 2017 at 11:22
1

try this code to handle duplicate entries and show echo message:

  $query = "INSERT INTO ".$table_name." ".$insertdata;
                if(mysqli_query($conn,$query)){
                    echo "data inserted into DB<br>";                   
                }else{
                   if(mysqli_errno($conn) == 1062)
                       echo "duplicate entry no need to insert into DB<br>";
                   else
                    echo "db insertion error:".$query."<br>";

                }//else end
0

With mysql_error() function http://php.net/manual/en/function.mysql-error.php

1
  • this just turns on error reporting, as far as i can tell. thanks anyway. Jun 30, 2010 at 6:30
0

Use mysql_errno() function, it returns the error numbers. The error number for duplicate keys is 1062. for example

$query = mysql_query("INSERT INTO table_name SET ...);
if (mysql_errno() == 1062){
    echo 'Duplicate key';
}
0

This is my full code that I used and works perfect. Its PDO friendly, and can handle your error easily, (once you have used die to discover what that is. Then you can copy the error message from there, and enclose it in an if. This came from a signup page, where I wanted to redirect to the login page, if the primary key (email) was found, and produced an error.

function insertUserDetails($email, $conn){

  try {
      $query = $conn->prepare ("INSERT INTO users (emailaddress) VALUES (:email)");
            $query ->bindValue('email', $email);
            $query->execute();
        }
  catch (PDOException $e) {

      if(str_contains($e, '1062 Duplicate entry')) {
          header("Location: login.php");

      }
          die("Error inserting user details into database: " .  $e->getMessage());

  }
}
0
  INSERT **IGNORE** into sales(id,order_date,amount)
  values(1, '2021-01-01', 250)

the IGNORE parameter stops generating and error but the duplicate entry is still not allowed.

$affectedRows = mysqli_stmt_affected_rows($stmt);
$newRowId = mysqli_insert_id($dbConn);

To error check If duplcate entry without php or mysql raising error ...

  /* -------------------------------------------------------
    the function that will securely place the new data
    into the database table
  ------------------------------------------------------- */
function insertIntoDatabase($dbConn, $tablename, $userData) 
{
  /*
    Generate placeholders for prepared statement 
    [$userData] is associate array ie    "firstname" => "henry"
    with the part left of => being the exact database column
    name and the part right of => being value inserted in column
  */
  $placeholders = rtrim(str_repeat('?, ', count($userData)), ', ');
  // Generate comma-separated list of column names
  $columns = implode(', ', array_keys($userData));
  // Construct the SQL query for insertion
  $sql = "INSERT IGNORE INTO $tablename ($columns) VALUES ($placeholders)";
  // Prepare the SQL statement
  $stmt = mysqli_prepare($dbConn, $sql);
  // Bind parameters to the prepared statement
  mysqli_stmt_bind_param($stmt, str_repeat('s', count($userData)), ...array_values($userData));
  // Execute the prepared statement to insert data into the database
  mysqli_stmt_execute($stmt);

   /*
    feedback on success or faliure
    if [$affectedRows] = 0 and ][$newRowId] = 0
    then we know nothing was added to database
   */
  $affectedRows = mysqli_stmt_affected_rows($stmt);
  $newRowId = mysqli_insert_id($dbConn);

  return [$affectedRows, $newRowId];
}

refer to https://vb6code.com/code-php-insert-data-into-mysql-database.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.