php - 检查数据库中是否已存在电子邮件

标签 php mysql sql email

我有一个连接到数据库的测验表单,但是我需要防止插入重复的电子邮件条目。 我尝试过以下方法:

//Check for duplicate email addresses
            function checkEmail($email){
                $sql = DB::select('email')->from('myquiz')->where('email','=','$email')->execute(); 

                $result = mysql_result(mysql_query($sql),0) ;

                if( $result > 0 ){
                die( "There is already a user with that email!" ) ;
                }//end if
            }

但是我仍然收到重复的条目,这是我的所有代码(可能是我没有在正确的位置运行它?)

 public function action_myquiz() {
    $this->template->styles['assets/css/myquiz.css'] = 'screen';
    $this->template->jscripts[] = 'assets/scripts/myquiz.js';
    $this->template->content = View::factory('quiz/myquiz');
        $this->template->content->thanks = false;
        if ($this->request->post('entry')) {
            $post = $this->request->post('entry');

            //Check for duplicate email addresses
            function checkEmail($email){
                $sql = DB::select('email')->from('myquiz')->where('email','=','$email')->execute(); 

                $result = mysql_result(mysql_query($sql),0) ;

                if( $result > 0 ){
                die( "There is already a user with that email!" ) ;
                }//end if
            }

            // save participant's info
            $stmt = DB::query(Database::INSERT, 'INSERT INTO `myquiz` (`first_name`, `last_name`, `email`, `confirm_email`)
                                                                        VALUES (:first_name, :last_name, :email, :confirm_email)');                                                     
            $stmt->param(':first_name', $post['first_name']);
            $stmt->param(':last_name', $post['last_name']);
            $stmt->param(':email', $post['email']);
            $stmt->param(':confirm_email', $post['confirm_email']);
            try {
                $stmt->execute();
            //  var_dump($post);
            } catch (Exception $e) {
                FB::error($e);
            }

            $this->template->content->thanks = true;
        }
    }

最佳答案

两个问题:

  1. 您从未调用 checkEmail() 函数,因此它永远不会运行。您应该从函数中删除该代码,或者只在需要运行的地方调用该函数。
  2. 在该函数中,您将检查是否存在字面上等于“$email”的电子邮件。 PHP 只会解析双引号中的变量 - 更改该行以使用 where('email','=',"$email") 代替。

关于php - 检查数据库中是否已存在电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758323/

相关文章:

mysql - Yii:获取每个月的热门用户和年底的热门用户的 SQL 查询

mysql - SQl查询 同一张表不同条件下的多个select语句

PHP 断开和 mysql 连接

c# - 排行榜,排名查询,如何返回高于/低于用户排名的行

PHP每日奖金

php - 如何使用 MYSQLi 连接三个表?

php - 将数据插入 MySQL 不起作用

php - 在php中的for循环中将元素推送到数组

iphone - 如何使用 UISegmentedControl 更改 tableview 中的数据源

php - MySQL将字段结果乘以另一个字段的编号