猿问

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

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


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

            }

        }

    }


呼啦一阵风
浏览 111回答 3
3回答

一只萌萌小番薯

您想要做的是修改表单验证规则,如下所示:只需is_unique[tablename.fieldname]向表单验证添加规则即可。例如:$this->form_validation->set_rules('emailid','Email&nbsp;id','required|valid_email|is_unique[yourTableName.yourEmailFieldName]');顺便说一句:您也可以在电子邮件规则中使用修剪

慕森王

您也可以分配您的自定义验证方法$this->form_validation->set_rules('emailid','Email id','required|valid_email|callback_username_check');&nbsp; &nbsp; public function username_check($str)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//your db query to check email exists and return true or false&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答