Martin
Martin

Reputation: 39

Check if email already exists and FILTER_VALIDATE_EMAIL in same function

I am trying to allow users to edit their email address in my PHP system but also prevent them from setting one that already exist, I am also trying run them through FILTER_VALIDATE_EMAIL. However it stops somewhere for me. The checks works fine in same function, but updating the the new one if the checks that I tried to setup are passed doesn't work. I am using a HTML form for updating them. I thought I did it right, I read here check if email exists in MySQL database that it should be possible to do it this way.

Here's my code, does anyone see what I am doing wrong? Where am I missing out?

function EmailCheck($sql) {

if (isset($_POST['email'])) {
    $newemail = $_POST["email"];

    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        echo "Invalid e-mail, please try a different.";
        exit;
    }

    $check_email = $sql->query("SELECT email FROM auth WHERE email='$newemail'");
    if ($check_email-> num_rows) {
        echo "E-mail is already in use.";
        exit;
    }
} 
else {
   mysqli_query($sql, "UPDATE auth SET email='$newemail' WHERE username = '$this->username'");
   header("Location: userinfo.php");
   exit;
 }
}

Upvotes: 0

Views: 1515

Answers (1)

bsguy
bsguy

Reputation: 91

Your Update query looks like it is in the wrong place. According to your code, if the posted email value is not set, you are updating the DB. I am guessing that is not what you want to do. The other problem I see is you are only passing the $sql variable to the function. The posted value will never be set.

//initalize flags
$flag1 = "no";
$flag2 = "no";
if( isset($_POST['email'])){
     if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
         echo "Invalid e-mail, please try a different.";
         exit;
    }else{
         //use flag here for for last if
         $flag1 = "yes";
    }
    $check_email = $sql->query("SELECT email FROM auth WHERE email='$newemail'");
    if ($check_email-> num_rows) {
        echo "E-mail is already in use.";
        exit;
    }else{
         //set 2nd flag here
         $flag2 = "yes";
    }

    if( $flag1 == "yes" && $flag2 == "yes"){
        //update query for new email here
    }
}else{
     //do something when no email is posted
}

Upvotes: 2

Related Questions