在CodeIgniter中,可以通过自定义表单验证器来比较表单输入数据与数据库数据。下面是一个实现的步骤:
Custom_validator
,并将其放置在CodeIgniter的application/libraries
目录下。<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Custom_validator
{
protected $CI;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->database(); // 加载数据库类
}
// 自定义验证规则方法
public function compare_data($str, $field)
{
list($table, $column) = explode('.', $field, 2);
$query = $this->CI->db->select($column)
->from($table)
->where($column, $str)
->get();
if ($query->num_rows() === 0) {
return FALSE; // 数据库中不存在该数据
} else {
return TRUE; // 数据库中存在该数据
}
}
}
application/config/form_validation.php
中,添加自定义验证规则的配置。$config = array(
'custom_validation' => array(
array(
'field' => 'input_field',
'label' => 'Input Field',
'rules' => 'required|compare_data[table_name.column_name]'
)
)
);
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Your_controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->library('custom_validator'); // 加载自定义验证器类
}
public function your_form_submit()
{
$this->form_validation->set_rules($this->config->item('custom_validation'));
if ($this->form_validation->run() === FALSE) {
// 验证失败
} else {
// 验证成功
}
}
}
在上述代码中,compare_data
方法用于比较表单输入数据与数据库中的数据。在配置文件中,compare_data[table_name.column_name]
指定了要比较的数据库表和字段。在控制器中,通过加载自定义验证器类,并在表单验证规则中使用compare_data
规则来调用自定义验证规则。
这样,当表单提交时,CodeIgniter会自动调用自定义验证器类中的compare_data
方法进行验证,根据返回结果判断验证是否通过。
注意:以上代码仅为示例,实际应根据具体情况进行调整和扩展。
领取专属 10元无门槛券
手把手带您无忧上云