PHP how to check mail already in MySQL database?

Hi I'm asking for help from all PHP gods on Stackoverflow :)

I have created an email registration form (just 1 email field) that can validate with Ajax and post a new email to the database from a basic PHP script I found.

However, the next step I have to take is to check if the email is in the database before adding it. There are a few questions on the Stack and I've tried all the answers to no avail :( I'm not a PHP guy and haven't been able to hack it yet.

Below is my current insert.php file that works and adds a new email field to the database. However, the code below is the last one I tried to use to validate an already existing email, but I am getting a send data error.

PHP working file to add email

$con = mysql_connect("localhost","root","root");
if (!$con)
    die('Could not connect: ' . mysql_error());

mysql_select_db("mydatabase", $con);

$sql="INSERT INTO newsletter (email)

    if (!mysql_query($sql,$con)) {
        die('Error: ' . mysql_error());

    echo "Thanks for subscribing!"; //Text on page
    //header("Location: /thankyoupage.php"); //Redirect page



UPDATED CODE using PDO The code below works for adding emails, however allows duplicate ...

/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'root';
/*** email ***/
$email    = '$_POST[mail]';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=mydatabase", $username, $password);

//$query = SELECT count(*) AS `total` FROM `data` WHERE `email` = '{$request}'

$query = SELECT COUNT(*) as 'count' FROM `data` WHERE email = '$_POST[mail]';
$row = mysql_fetch_assoc(mysql_query($query));

if($row['total']) {
    echo 'Sorry email already exists';
else {
    /*** echo a message saying we have connected & added email ***/
    echo 'Thanks for subscribing!';

    /*** INSERT data ***/
    $count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");

/*** echo a message saying we have connected & added email ***/
//echo 'Thanks for subscribing!';

/*** INSERT data ***/
//$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");

/*** echo the number of affected rows ***/
/*echo $count;*/

/*** close the database connection ***/
$dbh = null;
catch(PDOException $e)
echo $e->getMessage();


Thanks in advance for someone with time to take a look at this :)

Additional Notes: My database table is called a newsletter and there are 2 fields (ID numbers only) and (email)


source to share

1 answer

if the email is a unique key that would be simple

$email = mysql_real_escape_string($_POST['mail']);
$sql="INSERT IGNORE INTO newsletter (email) VALUES ('$email')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_affected_rows()) {
  header("Location: /thankyoupage.php"); //Redirect page
} else {
  //already exists




All Articles