I’m trying to figure out the best way to deal with duplicate entry errors when using PHP and MySQL. I’ve got this code that’s supposed to catch the error, but it’s not working right:
<?php
try {
$query = "INSERT INTO organizations (org_id, name, status, logo, contact, email)
VALUES ('ORG001', 'GreenEarth', 1, '/images/green_earth.png', 'John Doe', '[email protected]')";
$result = mysqli_query($connection, $query);
} catch (Exception $e) {
if (mysqli_errno($connection) == 1062) {
echo 'Oops! That ID already exists.';
}
}
?>
I know 1062 is the right error code for duplicates, but it’s not catching it. Should I be using PDO instead? I’m pretty new to this.
All I want is to show a simple message to the user when they try to add a duplicate primary key. Any ideas on how to do this? Thanks!
hey there! instead of using try-catch, u could use mysqli_error() to check for errors after the query. something like:
if (!mysqli_query($connection, $query)) {
if (mysqli_errno($connection) == 1062) {
echo ‘oops, that ID already exists!’;
}
}
this should catch the duplicate entry error. hope it helps!
I’ve been down this road before, and I can tell you that using PDO can definitely make error handling smoother. Here’s what worked for me:
try {
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO organizations (org_id, name, status, logo, contact, email) VALUES (?, ?, ?, ?, ?, ?)');
$stmt->execute(['ORG001', 'GreenEarth', 1, '/images/green_earth.png', 'John Doe', '[email protected]']);
} catch (PDOException $e) {
if ($e->getCode() == '23000') {
echo 'Oops! That ID already exists.';
} else {
// Handle other errors
echo 'An error occurred: ' . $e->getMessage();
}
}
This approach has been more reliable for me, and it’s easier to handle different types of errors. Plus, prepared statements help prevent SQL injection. Give it a shot and see if it works better for you!