繁体   English   中英

如何使用codeigniter检查用户名是否已存在

[英]how to check if username already exists using codeigniter

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

我为CRUD尝试了这个教程

<?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');
            }
        }
    }

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

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

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

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

    $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";
}

希望这会帮助你...只是理解逻辑

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

$this->form_validation->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
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM