Hi everyone,
I have a html form with the action field set as PHP_SELF. It asks for a users name and email. When they submit the form, a success message appears where the form was and the details are added to a MySQL database. That much I have working.
However, I need to add some PHP that will prevent duplicate email entries. This is what I have so far:
[php]<?php
//connect to the database
$dbc = mysqli_connect(‘localhost’, ‘root’, ‘password’, ‘database’) or die(‘Error connecting to MySQL server.’);
if(isset($_POST[‘register’])){
$name = mysqli_real_escape_string($dbc, trim($_POST[‘name’]));
$email = mysqli_real_escape_string($dbc, trim($_POST[‘email’]));
//create the insert statement
$query = “INSERT INTO tablename(name, email, date) VALUES (’$name’, ‘$email’, now())”;
//insert record into the table
$result = mysqli_query($dbc, $query) or die(‘Error querying the database’);
//display thank you to user
echo “Success - you have been added.”;
//close the connection
mysqli_close($dbc);
}
else {
?> [/php]
[code]<form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" name="newsletterform">
<input class="news" name="name" placeholder="Name" required>
<input class="news" name="email" type="email" placeholder="Email" required>
<input class="news" id="submitright" name="register" type="submit" value="Subscribe">
</form>[/code]
[php] <?php } ?>[/php]
So the above does the basics, takes the details and adds them to a database.
I have found the following code block to prevent duplicates - but when I add it, it throws everything out. Where would I place this code to get the form working correctly?
[php]$check=mysqli_query($dbc,"select * from tablename where email=’$email’ ");
$checkrows=mysqli_num_rows($check);
if($checkrows>0) {
echo “customer exists”;
} else { [/php]
Any help would be great, Andy