Search code examples
phpmysqlpdo

Checking DB for existing record with PHP PDO


I am trying to check if the database has the record to prevent duplicates. I am using the following code:

$stmt = $db->prepare('SELECT * FROM newsletter WHERE useremail=:useremail');
    $stmt->bindParam(':useremail', $_GET['useremail'], PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        echo "<script type='text/javascript'>Swal.fire('Info', 'This email is already registered.','info')";
    } else {
        $kaydet = $db->prepare("INSERT INTO newsletter SET useremail=:useremail");
        $insert = $kaydet->execute(array('useremail' => $_POST['useremail']));

        if ($insert) {
            header("Location:../index.php?status=success");
            exit;
        } else {
            header("Location:../index.php?status=error");
            exit;
        }
    }

I aim to prevent form submission for duplicate records. But this is not working. Any help would be appreciated. Thank you.


Solution

  • The problem with doing SELECT, check result, do INSERT, in PHP is that it is subject to race conditions. One thread could be about to do the insert just as the other selects no rows and about to also do an insert, and now you have duplicates.

    When confronted with this situation, let the database handle it.

    A unique index on useremail (or primary key), for the table will resolve this.

    Attempt the insert, if you get a duplicate key exception, then that's when you fire 'This email is already registered.', otherwise its a successful addition.