-1

I'm currently trying to ensure no duplicate emails are allowed to be entered within my mySQL database, I've marked stud_email as unique within the database I'm just struggling to alert the message. This is what I've got so far, am I on the correct path?

if (isset($_POST['submit'])) {
    $email = $_POST['email'];

    $check = mysqli_query($conn, "SELECT * FROM students WHERE stud_email = '$email'");
    $checkrows = mysqli_num_rows($check);

    if ($checkrows > 0) {
        echo '<script>alert("Student email already exists")</script>';
    } else {
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    Possible duplicate of [Prevent duplicate data being entered into mysql database](https://stackoverflow.com/questions/20081424/prevent-duplicate-data-being-entered-into-mysql-database) – Masivuye Cokile Mar 08 '18 at 12:03
  • call that email specifically , using : select email from students where email = check email and then continue. –  Mar 08 '18 at 12:24
  • I believe OP is asking how to (accurately) detect a DUPLICATE KEY error from the database. This is not a duplicate of "Prevent duplicate data being entered into mysql database" – RandomSeed Mar 08 '18 at 13:26
  • Does this answer your question? [How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)](https://stackoverflow.com/questions/22252904/how-to-check-if-a-row-exists-in-mysql-i-e-check-if-an-email-exists-in-mysql) – Dharman Feb 26 '20 at 20:19

1 Answers1

-2
$check = mysqli_query (SELECT count(*) FROM students WHERE stud_email = '$email');

Use Count to check whether the email is already in your database. If the count is greater than 1 then check it using IF condition in your JSP

if($check>0) {
     echo '<script>alert("Student email already exists")</script>';
}
vinieth
  • 1,204
  • 3
  • 16
  • 34