TonyCrudor
TonyCrudor

Reputation: 103

Using PHP Check Email ID Already Exist Or Not in Database

I'm trying to check if an email already exist in database and if exists, show message on the screen and don't run the PHPMailer. So I'm using this code below. the email that already exists is not saved in the database as I want, but the PHPMailer still run and the message does not appear.

<?php

include_once 'includes/dbh.php';
require  'email/PHPMailerAutoload.php';

$email = $_POST['emailFor'];

$sql = mysqli_query($conn, "SELECT * FROM `people` WHERE email=?");
$stmt = $conn->prepare($sql); 
$stmt->bind_param("i", $email);
$stmt->execute();
$result = $stmt->get_result(); 
$query = $result->fetch_assoc(); 


if(mysqli_num_rows($result)>0){
    echo "This email has already been registered";
} else {
    // ==== INSERT VALUES INTO DB 
    $stmt = mysqli_prepare($conn, "INSERT INTO people (email) VALUES (?);");

    mysqli_stmt_bind_param($stmt, 's', $email);
    $result = mysqli_stmt_execute($stmt);
}

$mail = new PHPMailer;

$mail ->isSMTP();

Upvotes: 3

Views: 3721

Answers (1)

Amir MB
Amir MB

Reputation: 3418

A good way is to create a UNIQUE index on the email column, then you could use INSERT IGNORE INTO instead of simple insert, and then you could check affected_rows to determine if the insertion was successful or the email already exists in the table:

$stmt = mysqli_prepare($conn, "INSERT IGNORE INTO people (email) VALUES (?);");

mysqli_stmt_bind_param($stmt, 's', $email);
$result = mysqli_stmt_execute($stmt);

if(mysqli_affected_rows($result) === 1) {
    // email was new, here you should send the email
    $mail = new PHPMailer;
}
else {
     echo "This email has already been registered";
}

Upvotes: 3

Related Questions