首页 > 解决方案 > 使用 CodeIgniter 检查字段值是否唯一

问题描述

我正在尝试检查添加到数据库中的值是否是unique.

这是我正在使用的代码,但即使我知道该号码已经在数据库中,也in_array()不会返回。true我是误会result_array()还是something?

//Check if Serial is Already in Database 
$this->db->select('fldUserSensorID');
$sensorqry = $this->db->get("tblMonitoringSensors");
$result = $sensorqry->result_array();

if (in_array($this->input->post('serialNumber'), $result)) {
    $attempt=false;
}

标签: phparraysdatabasecodeigniterunique

解决方案


您正在使用result_array()应该有这样的数据Array: -

Array(
  0=>Array("fldUserSensorID"=>1),
  1=>Array("fldUserSensorID"=>3),
  2=>Array("fldUserSensorID"=>9)
)

所以你应该试试这个:

$optimized_result=array_column($result, 'fldUserSensorID');
if (in_array($this->input->post('serialNumber'), $optimized_result)) {
                $attempt=false;
}

推荐阅读