-1

Well that's basically what I'm trying to do.

I have a form that saves into the database, now if the email in this case, already exist, it gives me the error message that " user already exist.

and since I am echoing out the values from the database into the form fields it gives me that " user already exist" error every time i push update. If don't echo out the value, when I'm updating the form, it saves an empty email address, or filter_validate_Email function tells me that the email is not valid.

I tried and succeed when fixed the problem with check boxes but that's kind of messy and ugly so I am trying if else statement but with no luck. Any tips on how to manage this ?

Ill send you some code.

if(email_exists($_POST['email'])===($_POST['email'])){

    } 

    if(email_exists($_POST['email'])){
        $errors[] = 'email already registered';
    }

With that statement i was thinking of, if the $_POST email is equal to $_POST email. do nothing, but if the email exist from email_exist function. error email already exist.

    if(empty($errors)){ 
        set_profile_info($_POST['firstname'],
        $_POST['lastname'],
        $_POST['username'],
        $_POST['email'],
        $_POST['about']);
    }
}

email_exists query

function email_exists($email){
    global $db;
    $st = $db->prepare("SELECT * FROM user WHERE email=?" );
    $st->bindParam(1, $email);
    $st->execute();

    if($st->rowCount() ==1){
        return true;
    }
    else{ 
       return false;
    }
} 

There are probably millions of other ways, but i cant figure anything else. thanks

4

1 回答 1

1

您应该在“电子邮件”字段上使用 UNIQUE 索引

ALTER TABLE yourtable
ADD UNIQUE INDEX EMAIL_UNIQUE(email);

那么当您尝试使用电子邮件添加用户时,它会给您错误/异常,具体取决于您使用的 sql 引擎。

我注意到你使用全局变量是个坏习惯。最好创建 Registry 或 Singleton 来获取数据库对象。

http://www.phpeveryday.com/articles/OOP-Pattern-Registry-Introduction-Registry-Pattern-P240.html http://en.wikipedia.org/wiki/Singleton_pattern

你也做了一件奇怪的事情。为什么你使用“===”这意味着具有相同类型的“EXACT”变量,然后你将字符串与布尔值进行比较,它总是返回false。

改变

if(email_exists($_POST['email'])===($_POST['email'])){

if(email_exists($_POST['email'])==($_POST['email'])){

或者

if(email_exists($_POST['email'])===((bool)$_POST['email'])){

改变

if(email_exists($_POST['email'])===($_POST['email'])){

} 

if(email_exists($_POST['email'])){
    $errors[] = 'email already registered';
}

$emailExists = email_exists($_POST['email'])
if(emailExists == $_POST['email']){
  //doing your stuff when email exists
} 

if(emailExists){
    //doing other stuff when email exists
    $errors[] = 'email already registered';
}

当您更改它时,调用数据库的函数将只被调用一次。

于 2013-04-17T13:02:18.787 回答