Search code examples
phpmysqlsql-servermamp

How to avoid duplicate emails php / sql?


I used this code and I don't know what is the problem and I used different codes as well

what I want to do to check and not allow the user to add his email twice

<?php
include("includedb.php");
//declare variables
$name        = $_POST['name'];
$email       = $_POST['email'];
$tel         = $_POST['tel'];
$gift        = $_POST['gift'];
$formName    = $_POST['formName'];
$formEmail   = $_POST['formEmail'];
$formEmirate = $_POST['formEmirate'];
$birthday    = $_POST['birthday'];
$date        = $_POST['date'];

$result = mysqli_query("SELECT * FROM  users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates

$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist

if ($num_rows == 0) { //if there are no duplicates...insert
    $sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
    if (!mysqli_query($sql)) {
        die('Error: ' . mysqli_error());
    }
}

mysqli_close();

header("location: thank-you.html?remarks=success");

?>

Solution

  • thanks for support I found what has worked with me please find the code below and please advise me how to make it secure and protect it from sql injection

    if(isset($_POST['submit'])){
    $name= $_POST['name'];
    $email= $_POST['email'];
    
    
    $result = mysqli_query($conn,"SELECT * FROM  test WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
    $num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
    
     if(($num_rows) > 0){
         echo "A record already exists."; 
         exit;
        }
    
    else{
    $sql = "INSERT INTO test (name, email)
    VALUES ('$name', '$email')";
    if (!mysqli_query($conn,$sql))
      {
      die('Error: ' . mysqli_error());
      }
    }
    
    if($result) {
    
              header("Location: game.html");
    
    }else{ echo "Not Successful"; }
    
    mysqli_close();
    }
    ?>
    
    <!DOCTYPE html>
    <head>
    
    </head>
    <body>
    
    <h2>Enter your Name and Email</h2>
    <form method="post">
        <p><strong>First Name:</strong><br /> <input type="text" name="name" /></p>
        <p><strong>email:</strong><br /> <input type="email" name="email"/></p>
    
        <input type="submit" name="submit" value="Add Customer" />
    </form>
    
    
    
    </body>
    </html>