I'm setting up this newsletter subscription form to communicate with my database, but before sending the information(email) I just want to validate it. However when I enter wrong or empty data, it displays both error messages. I'm no expert on PHP but it seems I'm missing some closing brackets or something.. I've fiddled around now for a while with no success, so I turn for help to you guys again :)
<?php
$host = "XXX";
$username = "name";
$password = "XXX";
$database = "base";
$connect = @mysql_connect($host, $username, $password) or die (@mysql_error());
$selectdb = @mysql_select_db($database, $connect) or die (@mysql_error());
if(isset($_POST['submit'])){
$email = $_POST['email'];
if(empty($email)){
echo "Hmm, you did not anything..";
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
echo "This email not valid";
}
else{
@mysql_query("INSERT INTO newsletters SET email='$email'");
echo "Thanks you";
}
}
?>
Thank you!!
You're currently using the following structure:
if (condition) {
}
if (condition) {
}
else (condition) {
}
Change the structure to:
if (condition) {
}
elseif (condition) {
}
else (condition) {
}
That way, the elseif
statement will get executed ONLY if the first if statement evaluates to FALSE
.
Also, in your preg_match
statement, you're using the variable $email_address
which isn't defined anywhere, as far as I can see.
Change it to $email
:
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email))
Hope this helps!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments