0

I need to make an error, if an email already exists in my database.

I have made this code, but it doesn't work

`<?php`

// CONNECT TO DATABASE

$mysqli = new mysqli("database", "username", "password","database_name"); // creates 

$mail = $_POST['mail']; //from input
$result = mysql_query("SELECT * FROM Newsmail WHERE mail='" . $mail . "'");
if (mysql_num_rows($result) == 1)
{
echo "Error";
}


else {
//sql
$sql = "INSERT INTO `database_name`.`Newsmail` (`newsmail_id`, `mail`) VALUES (NULL, \'" . $_GET['mail'] . "\');";

//INSERT TO DATABASE
$insert =  $mysqli->query($sql);

}

?>

2 Answers2

0

If email is an unique key, Try INSERT IGNORE

$mail = mysql_real_escape_string($mail);
$sql="INSERT IGNORE INTO Newsmail (email) VALUES ('$email')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);

if (mysql_affected_rows()) {
echo 'registration successfully';
} else {
echo 'already exists';
}
Abhishek Sharma
  • 6,689
  • 1
  • 14
  • 20
0

Following mistake in your code

1)You are mixing mysql and mysqli into your code

2)Your query is open for sql injection

3)You having confusion in $_POST and $_GET method in your code

4)NO error checking method to find out error

<?php

// CONNECT TO DATABASE

$mysqli = new mysqli("database", "username", "password", "database_name"); // creates 

$mail = $mysqli->real_escape_string($_POST['mail']);
$result = $mysqli->query("SELECT * FROM Newsmail WHERE mail='" . $mail . "'");
if ($mysqli->num_rows($result) == 1) {
    echo "Error";
} else {
//sql
    $sql = "INSERT INTO `database_name`.`Newsmail` (`newsmail_id`, `mail`) VALUES (NULL, '" . $mail . "')";

//INSERT TO DATABASE
    $insert = $mysqli->query($sql);
}
?>
Saty
  • 22,443
  • 7
  • 33
  • 51