AndB
AndB

Reputation: 139

Display error if the email address entered in form already exists

How do I use "emailaddress" as the only duplicate entry that provides a error?

A lot of the answers I've found use mysql_query but I want to use mysqli.

<?php
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
?>

Upvotes: 0

Views: 951

Answers (2)

nvanesch
nvanesch

Reputation: 2600

WARNING! the posted code and this answer (as i am only addressing the question now) contain big SQL injection leaks. Please read up on SQL injection and use escaping or prepared statements.

<?php

$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '".$_POST[emailaddress]."'";
$existsResult = mysqli_query($con, $existsQuery);

if($existsResult->fetch_object()->count > 0)
{
    echo "email already exist";
}
else
{
    $sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";

    if (!mysqli_query($con, $sql)) {
        die('Error: ' . mysqli_error($con));
    }
    echo "1 record added";
}

mysqli_close($con);
?>

Upvotes: 2

Manoj Purohit
Manoj Purohit

Reputation: 3453

simply make emailaddress unique in your table.

Upvotes: 1

Related Questions