So I'm trying to input records into a database. Everything inserts fine, but how do I check/make sure that I am not inserting the same information into the database. I tried the following code, but it always inserts the info no matter if its the same or not. How can I can check and stop duplicate entries?
try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO `users`(`name`, `username`, `avatar`) VALUES (:name, :username, :avatar)";
$statement = $link->prepare($query);
$statement->execute(array(
':name' => $_POST['name'],
':username' => $_POST['username'],
':avatar' => $_POST['avatar']
));
echo 'added!';
} catch(PDOException $e) {
if ($e->errorInfo[1] == 1062) {
// duplicate entry, do something else
echo 'this user has already been added';
} else {
// an error other than duplicate entry occurred
echo "Exception caught: $e";
}
}