简体   繁体   English

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

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

I want to create a login form validation. 我想创建一个登录表单验证。 In that I need to check whether the username and email already exist. 在那里我需要检查用户名和电子邮件是否已经存在。 If exist display error 如果存在显示错误

I tried this tutorial for CRUD 我为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');
            }
        }
    }

What you want to do is modify your rules for the form validation as below : 您要做的是修改表单验证的规则,如下所示:

Just add is_unique[tablename.fieldname] rules to the form validation. 只需将is_unique[tablename.fieldname]规则添加到表单验证中即可。 for Example: 例如:

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

BTW: You could also use trim in the rules for your email 顺便说一句:您也可以在电子邮件的规则中使用修剪

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

Hope this will help you out.. just understand the logic 希望这会帮助你...只是理解逻辑

Also u can assign your custom validation method 您也可以指定自定义验证方法

$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