Hi I'm calling out for help from all the PHP Gods on Stackoverflow :)
I've created an email signup form (just 1 field for email), that is able to 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 do is check if an email is already in the database before adding it. There are several questions exactly like this on Stack and I've tried all the answers however to no avail :( I'm not a PHP guy and haven't been able to hack it right yet.
Below is my current insert.php file which does work and does add a new email field into the database. However the code below that is the latest I've tried to use to check for an already existing email, but I get a send data error.
Working PHP file to add email
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydatabase", $con);
$sql="INSERT INTO newsletter (email)
VALUES
('$_POST[mail]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Thanks for subscribing!"; //Text on page
//header("Location: /thankyoupage.php"); //Redirect page
mysql_close($con)
?>
UPDATED CODE using PDO Code below works to add emails, however still allows duplicates...
<?php
/*** 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 anyone with the time to take a look at this :)
Extra Notes: My database table is called newsletter and there are 2 fields (id - numbers only) & (email)