0

I want to be able to set the following:

1) If the email already exists to return an error 2) If successful to return an error 3) if error to return error

At the moment it works, but allows you to add same email address and sends successful response but need to add one for existing email

$('form').submit(function(){

// check if passwords match; you might want to do more thorough validation
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var emailaddressVal = $("#email").val();
    if(emailaddressVal == '') {
            $("#email").after('<span class="error">Please enter your email address.</span>');
            hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
            $("#email").after('<span class="error">Enter a valid email address.</span>');
            hasError = true;
    } else if(hasError == false) {
            // make ajax post request and store the response in "response" variable
     $.post('submit.php', $(this).serialize(), function(response){

         // process response here (assume JSON object has boolean property "ok"
         if(response.ok==true){
             // sweet, it worked!
             alert('OK!');
         }else{
             // handle error
             alert('Ooops');
         }
     }, 'json');
    }

    // stop the form from being submitted
return false;
});

And the php is:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$con = mysql_connect("localhost","root",""); //Replace with your actual MySQL DB Username and Password
if (!$con) { die('Could not connect: ' . mysql_error()); } 
mysql_select_db("table", $con); //Replace with your MySQL DB Name

$first_name=mysql_real_escape_string($_POST['firstname']); 
$last_name=mysql_real_escape_string($_POST['lastname']); 
$email=mysql_real_escape_string($_POST['email']); 

$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')"; 

if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } 
echo "The form data was successfully added to your database."; 
mysql_close($con);
?>

Thanks!

Viral Shah
  • 2,263
  • 5
  • 21
  • 36
James Brandon
  • 1,350
  • 3
  • 16
  • 43
  • http://docs.jquery.com/Plugins/Validation/validate refer this link you can do it easily. – Dipesh Parmar Dec 04 '12 at 10:21
  • 3
    please.. dont use `mysql_*`! it's **deprecated**. Use **`PDO`**! (or `mysqli_*`) – StasGrin Dec 04 '12 at 10:27
  • and.. real escaping? [nice way to got all data lost](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) – StasGrin Dec 04 '12 at 10:28

4 Answers4

2

Just check for the email in the db before u add. Hope This Helps.

    <?php
    $first_name=mysql_real_escape_string($_POST['firstname']); 
    $last_name=mysql_real_escape_string($_POST['lastname']); 
    $email=mysql_real_escape_string($_POST['email']); 
    $sql = "SELECT * FROM email_list WHERE `email`='$email'";
    $res= @mysql_query($sql);
    if(@mysql_num_rows($res)>0)
    {
      echo "Email Already Exists" ;

    }
    else
{
 $sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')"; 

    if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } 
    echo "The form data was successfully added to your database."; 
  }
    ?>
bikash shrestha
  • 429
  • 2
  • 5
2
$sql="SELECT email FROM email_list WHERE email = '$email'";
$result = mysql_query($sql, $con) or die('Error: ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
  // Error - Email already exists
   echo "Error: The email address already exists."; 
} else {
   $sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')"; 

   if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } 
   echo "The form data was successfully added to your database."; 
}

mysql_close($con);

I have added a check to see if the email address already exists, and output an error if it does. There are also error outputs for mysql errors.

If you need the output to be formatted in a certain way, use JSON. But the above should get you started.

Kami
  • 19,134
  • 4
  • 51
  • 63
1

just add following line in end of you php file

$value = mysql_insert_id() > 0;

echo json_encode( array('ok'=> $value ) );
  • and what? getting `ok` when u'll insert another record with email already existed in table? – StasGrin Dec 04 '12 at 10:18
  • 1
    you need to check before execute insert query like –  Dec 04 '12 at 10:19
  • 1
    $sql="select count(*) idavail email_list where email = '".$email."'"; $result= mysql_query( $sql ); –  Dec 04 '12 at 10:20
  • `you`? not me:) author of questin. and thats not so easy, as you wrote here. before insert u may: 1. check if this field already exists... or 2. set this row unique. – StasGrin Dec 04 '12 at 10:21
  • answer isnt correct for now. even not close to be truth. edit? – StasGrin Dec 04 '12 at 10:21
  • $row = mysql_fetch_assoc( $result ); if( $row['idavail'] > 0 ){ echo json_encode(array('ok' => false )); exit; } –  Dec 04 '12 at 10:21
  • no this is correct first then you can say it is wrong or correct –  Dec 04 '12 at 10:23
  • and don't echo anything else –  Dec 04 '12 at 10:23
  • like `echo "The form data was successfully added to your database."; ` –  Dec 04 '12 at 11:03
1

jquery

$('form').submit(function(){

// check if passwords match; you might want to do more thorough validation
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var emailaddressVal = $("#email").val();
    if(emailaddressVal == '') {
            $("#email").after('<span class="error">Please enter your email address.</span>');
            hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
            $("#email").after('<span class="error">Enter a valid email address.</span>');
            hasError = true;
    } else if(hasError == false) {
            // make ajax post request and store the response in "response" variable
     $.post('submit.php', $(this).serialize(), function(response){

         // process response here (assume JSON object has boolean property "ok"
         if(response.ok=='0'){
             alert('required fields empty');
         }else if(response.ok=='1'){
               alert('email already exists');
         }
else if(response.ok=='2')
{
alert('thankyou for your input');
}
     }, 'json');
    }

    // stop the form from being submitted
return false;
});

php code

    <?php
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $con = mysql_connect("localhost","root",""); //Replace with your actual MySQL DB Username and Password
    if (!$con) { die('Could not connect: ' . mysql_error()); } 
    mysql_select_db("table", $con); //Replace with your MySQL DB Name

    $first_name=mysql_real_escape_string($_POST['firstname']); 
    $last_name=mysql_real_escape_string($_POST['lastname']); 
    $email=mysql_real_escape_string($_POST['email']); 

    if(empty($first_name) || empty($last_name) || empty($email) ) {

        echo json_encode( array('ok'=> '0' ) );
        exit();
    }

    $sql="Select * from email_list where email='".$email."' ";
    $sqll=mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
    $data=mysql_fetch_array($sqll);
    if($data['email']) {

        echo json_encode( array('ok'=> '1' ) );
        exit();

    }

    $sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')"; 
mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
    $value = mysql_insert_id() > 0;
    if($value)
    echo json_encode( array('ok'=> '2' ) );
    mysql_close($con);
    exit();
    ?>
danish hashmi
  • 484
  • 5
  • 12