簡體   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