繁体   English   中英

Check是CodeIgniter查询的字符串元素

[英]Check is a string element of CodeIgniter query

您好,我想检查是否是codeIgniter查询的字符串元素,所以我想使用数组。

我使用这种解决方案,但在两种情况下我都做错了。

 $data = array(
    'Firstname' => $ime ,
    'Lastname' => $prezime,
    'Nick' => $username,
    'EmailAddress' => $email,
    'Uid' => $uid,
);

$rs = $this->db->query("Select Nick FROM cms_cart_customers");
$array = $rs->result_array();
if(!in_array($data['Nick'],$array))
{
$this->db->insert('cms_cart_customers', $data);
}

result_array()函数即使您只有一列,也会返回一个多维数组。 您需要展平数组以线性搜索数组,请尝试如下操作:

$array = $rs->result_array();
$flattened = array();
foreach($array as $a) {
    $flattened[] = $a['Nick'];
}

if(!in_array($data['Nick'],$flattened)) {
    $this->db->insert('cms_cart_customers', $data);
}

Codeigniter查询将在associative array返回结果,而in_array()函数将in_array()

这是您可以执行此自定义is_in_array函数源的一种方法

//Helper function
function is_in_array($array, $key, $key_value){
  $within_array = false;
  foreach( $array as $k=>$v ){
    if( is_array($v) ){
        $within_array = is_in_array($v, $key, $key_value);
        if( $within_array == true ){
            break;
        }
    } else {
            if( $v == $key_value && $k == $key ){
                    $within_array = true;
                    break;
            }
    }
  }
  return $within_array;
}


$array = $rs->result_array();
if(!is_in_array($array, 'Nick', $data['Nick']))
{
    $this->db->insert('cms_cart_customers', $data);
}

其他方法

如果要避免重复输入,则应首先使用Select查询来检查表中是否已存在'Nick' = $username ,如果不存在,则发出插入

$rs = $this->db->get_where('cms_cart_customers', array('Nick' => $username));

//After that just check the row count it should return 0
if($rs->num_rows() == 0) {
    $this->db->insert('cms_cart_customers', $data);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM