【问题标题】:how to check if username already exists using codeigniter如何使用codeigniter检查用户名是否已经存在
【发布时间】:2019-05-20 10:46:58
【问题描述】:

我想创建一个登录表单验证。在那我需要检查用户名和电子邮件是否已经存在。如果存在显示错误

我为 CRUD 尝试了 this tutorial

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Insert extends CI_Controller {

        // For data insertion
        public function index(){

            //Setting validation rules
            $this->form_validation->set_rules('firstname','First Name','required|alpha');
            $this->form_validation->set_rules('lastname','Last Name','required|alpha');
            $this->form_validation->set_rules('emailid','Email id','required|valid_email');
            $this->form_validation->set_rules('contactno','Contact Number','required|numeric|exact_length[10]');
            $this->form_validation->set_rules('address','Address','required');

            if($this->form_validation->run()){
                $fname=$this->input->post('firstname');
                $lname=$this->input->post('lastname');
                $email=$this->input->post('emailid');
                $cntno=$this->input->post('contactno');
                $adrss=$this->input->post('address');
                //loading model
                $this->load->model('Insert_Model');
                $this->Insert_Model->insertdata($fname,$lname,$email,$cntno,$adrss);
                $this->load->view('insert');
            } else {
                $this->load->view('insert');
            }
        }
    }

【问题讨论】:

标签: php codeigniter codeigniter-3


【解决方案1】:

您要做的是修改表单验证的规则,如下所示:

只需将is_unique[tablename.fieldname] 规则添加到表单验证中。例如:

$this->form_validation->set_rules('emailid','Email id','required|valid_email|is_unique[yourTableName.yourEmailFieldName]');

顺便说一句:您也可以在电子邮件规则中使用 trim

【讨论】:

  • 我对 required 的所有内容都使用了 trim 我真的很惊讶它没有自动包含在 required 函数中。在我看来,想要 required 而不需要 trim 的极端情况是如此之小,不值得考虑。
【解决方案2】:
    $this->db->where('emailid', $email); // OTHER CONDITIONS IF ANY
    $this->db->from('tblusers'); //TABLE NAME
    echo $this->db->count_all_results();
if($this->db->count_all_results() > 0)
{
echo "Duplicate Record";
}
else
{
echo  "New record";
}

希望这对您有所帮助.. 只需了解逻辑

【讨论】:

  • 只要实现一个防止重复的规则就不需要那么多代码了。
  • 你是对的。如果他不理解,我写信是为了理解其背后的逻辑。谢谢你的回答非常正确。 @DylanKas
  • 将其转换为回调会很好。
【解决方案3】:

您也可以指定您的自定义验证方法

$this-&gt;form_validation-&gt;set_rules('emailid','Email id','required|valid_email|callback_username_check');

    public function username_check($str)
    {
           //your db query to check email exists and return true or false
    }

【讨论】:

    猜你喜欢
    • 2015-06-17
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多