You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter自定义重复邮箱/手机号错误提示并阻止重复数据插入

解决CodeIgniter中邮箱/手机号唯一性校验的提示与数据插入问题

你的问题核心在于:当检测到重复的邮箱/手机号时,原代码要么抛出异常导致页面报错,要么弹出提示后没终止后续的数据库插入逻辑。下面是兼顾友好提示和数据安全的完整修复方案:

1. 重构后端校验逻辑(核心修改)

我们需要在校验到重复数据时,立即终止后续代码执行,并输出友好的弹窗提示,彻底避免错误数据存入数据库。修改后的add_applicants方法如下:

public function add_applicants() { 
    $data = $this->input->post(); 
    $errors = [];

    // 校验手机号唯一性
    $mobile = $this->db->get_where('applicants', ['mobile_number' => $this->input->post('mobile_number')]); 
    if($mobile->num_rows() > 0) { 
        $errors[] = "该手机号已被注册"; 
    } 

    // 校验邮箱唯一性
    $email = $this->db->get_where('applicants', ['email_id' => $this->input->post('email_id')]); 
    if($email->num_rows() > 0) { 
        $errors[] = "该邮箱已被注册"; 
    } 

    // 存在错误时,提示并终止流程
    if(!empty($errors)) {
        $errorMsg = implode('\\n', $errors); // 拼接多个错误为换行提示
        echo "<script>alert('{$errorMsg}'); history.back();</script>";
        exit(); // 关键:终止后续代码,不执行上传和插入
    }

    // 以下仅在校验通过时执行
    $school_id= $this->input->post('school_code'); 
    $name_of_exam= $this->input->post('name_of_exam'); 
    $name= $this->input->post('name_candiadte'); 
    $exam = '';
    switch($name_of_exam){ 
        case '1': $exam='NMMS'; break; 
        case '2': $exam='NTS'; break; 
        default: $exam=''; // 新增默认值,避免未匹配时变量为空
    } 

    // 处理文件上传
    $file_name = '';
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] != UPLOAD_ERR_NO_FILE) { 
        $school_code = $this->Welcome_Model->getschoolData($school_id); 
        $config['upload_path'] = FCPATH . 'uploads/'. $school_code->name_of_the_school.'/'. $exam ; 
        
        // 自动创建上传目录(避免目录不存在导致上传失败)
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }

        $config['allowed_types'] = 'jpg'; 
        $config['max_size'] = 2000; 
        $config['remove_spaces'] = TRUE; 
        $config['overwrite'] = true; 
        $config['file_name'] = $name.'-'.date('Ymdhis') . '.jpg'; 
        $file_name = $config['file_name']; 

        $this->load->library('upload', $config); 
        $this->upload->initialize($config); 

        if (!$this->upload->do_upload('photo')) { 
            echo "<script>alert('图片上传失败:{$this->upload->display_errors()}'); history.back();</script>";
            exit();
        } 
    } 

    $data['photo'] = $file_name; 
    $insetapplicants = $this->Welcome_Model->insertApplicants($data); 

    if ($insetapplicants == 'Success') { 
        echo "<script> alert('新申请人添加成功'); window.location.href='dashboard'; </script>"; 
    } else {
        echo "<script> alert('添加失败,请重试'); history.back();</script>";
    }
}

2. 关键修改点说明

  • 错误终止机制:用数组收集所有校验错误,若存在错误则弹窗提示,并用exit()终止后续代码,彻底阻断数据库插入操作。
  • 体验优化:用history.back()让用户在提示后返回表单页面,保留已填写内容,避免重复输入。
  • 上传逻辑优化:新增目录自动创建逻辑,修改文件上传的判断条件,避免因目录不存在或无文件上传导致的异常。

3. 进阶优化:使用CodeIgniter表单验证类(推荐)

CodeIgniter自带的表单验证类可以更规范地处理校验逻辑,无需手动编写SQL查询,代码更简洁安全:

public function add_applicants() {
    // 加载表单验证库并设置规则
    $this->load->library('form_validation');
    $this->form_validation->set_rules('mobile_number', '手机号', 'is_unique[applicants.mobile_number]', [
        'is_unique' => '该手机号已被注册'
    ]);
    $this->form_validation->set_rules('email_id', '邮箱', 'is_unique[applicants.email_id]', [
        'is_unique' => '该邮箱已被注册'
    ]);

    if ($this->form_validation->run() == FALSE) {
        // 校验不通过时输出提示并返回表单
        $errorMsg = validation_errors();
        echo "<script>alert('{$errorMsg}'); history.back();</script>";
        exit();
    }

    // 后续的上传、插入逻辑同上面的代码...
}

这种方式利用框架自带的is_unique规则,既减少了重复代码,又能避免手动SQL可能出现的安全问题。

内容的提问来源于stack exchange,提问作者user12162912

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:13