I’m creating a site which requires a database for registration etc. I’m struggling to stop duplicate emails from happening

  php

So basically I have created the database which works fine. I have set up an HTML template that sends an email etc which for the most part works fine. However, I’m struggling to string some code together in my PHP that stops the user from entering a duplicate email address. PHP is not my strong point but in my head, it should make sense, So in the code below, the connection error works fine. the $result var keeps throwing error 500 so I changed the 0 in else if statement to 1 and changed $result to 0 and that works. When changing the 0 to 2 though it says error 500. Honestly, no idea how to debug PHP so I thought asking for help here is my best bet. (i took the email functions out to shorten the code)

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];

    $host = 'localhost';
    $username = 'un';
    $password = 'pw';
    $db = 'db';
    $conn = new mysqli($host , $username, $password, $db);

    $query = "SELECT count(email) FROM registration WHERE email='$email'";
    $result = mysqli_num_rows($query > 0);

    function createEmail(){
        if($conn->connect_error){
            die("Connection Failed : ". $conn->connect_error);
            // add header for this instance
        }else if($result > 0){
            die("There is already a user with that email!");
            // add popup for this instance
        }else{
            $insert = $conn->prepare("insert into registration(name, email) values(?, ?)");
            $insert->bind_param("ss", $name, $email);
            $insert->execute();
            header("Location: thankyou.html");
            $insert->close();
            $conn->close();
        }
    }
    createEmail($email);
?>

Source: Ask PHP

LEAVE A COMMENT