Mysql error message 1062 in php script

i have small php form with with id, firstname, lastname, mobileno , in which id is primary key which auto incremented where as mobileno column set unique in mysql table. I wanted to generate error message if duplicate mobileno trying to enter in database and stop record from storing in database. (duplicate error message need to be generated at front end (form page) rather than form.php file)Here is my php code

<form method="POST" action="form1.php">
<label>firstname</labe><input type = text name  = "fname" id = :"fname">
<label>Last name</labe><input type = text name  = "lname" id = :"lname">
<label>Mobile No</labe><input type = text name  = "mob" id = :"mob">
<input type = "submit" value = "submit">

here is form.php file

    // getting all values from the HTML form
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $mob = $_POST[mob'];
 $sql = "INSERT INTO iap2 (fname, lname, mob)
 VALUES ('$fname', '$lname', '$mob')"; 
    // send query to the database to add values and confirm if successful
    $rs = mysqli_query($con, $sql);
        echo "record already exists";

    // close connection


The 1062 error is what is supposed to happen (with reference to your other topic) when a duplicate value is entered to a unique column.
As stated, use a try/catch to catch the error and deal with it.
This is a case where you want an error, so you can use it in validation.

There are a number of issues but the main thing that sticks out is


Notice something missing?

1 Like

its by mistake here, where as in actual code nothing something like inverted comma is missing :slight_smile:

This is what I do to trap duplicate errors, it’s a bit rough and ready but it’s only for my use:

$query = "insert into car_makes (make) values (?)";
$pre = $dbc->prepare($query);
try {
   $ex = $pre->execute(array($make));
   $_SESSION['message'] = "Make " . $make . " added.";
   } catch (Exception $e) {
   if ($e->errorInfo[1] == 1062) {
     $_SESSION['message'] = "Make name already exists";
   } else {
     $_SESSION['message'] = "There was a problem creating your make. Contact support.";
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.