-1

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.

  • 3
    You're using `PDO::PARAM_INT` when binding a string? Have you tried `PDO::PARAM_STR` (or removing it completely since it defaults to string)? You're also using `$_GET['useremail']` for the first query and `$_POST['useremail']` in the second. Which is it? You also never close the ` – M. Eriksson Mar 08 '23 at 07:07

2 Answers2

0

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.

danblack
  • 12,130
  • 2
  • 22
  • 41
-1

i think the problem is with the

$stmt->bindParam(':useremail', $colour, PDO::PARAM_STR);

Use above instead of param int
https://www.php.net/manual/en/pdostatement.bindparam.php

General Grievance
  • 4,555
  • 31
  • 31
  • 45