0

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";
    }
}
MrPilot
  • 163
  • 2
  • 3
  • 9

1 Answers1

1

i am assuming that is the username that you don't want to duplicate, so you can check on you DB table on the row 'username' as UNIQUE.

hope it helped

Denis Nagy
  • 54
  • 4