简体   繁体   English

Check是CodeIgniter查询的字符串元素

[英]Check is a string element of CodeIgniter query

Hello I wanna check if is string element of codeIgniter query, so I wanna compere to arrays. 您好,我想检查是否是codeIgniter查询的字符串元素,所以我想使用数组。

I use this soulution but i get false in both case. 我使用这种解决方案,但在两种情况下我都做错了。

 $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);
}

The result_array() function returns you a multi-dimensional array, even with a single column. result_array()函数即使您只有一列,也会返回一个多维数组。 You need to flatten the array in order to search the array linearly, try something like this: 您需要展平数组以线性搜索数组,请尝试如下操作:

$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 query will return result in associative array and in_array() function will not going to do the trick. Codeigniter查询将在associative array返回结果,而in_array()函数将in_array()

Here is one way you can do this custom is_in_array function source 这是您可以执行此自定义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);
}

Other Method 其他方法

If you are trying to avoid duplicate entry, you should use a Select query first to check that the 'Nick' = $username is already present in table, if not then Issue an insert 如果要避免重复输入,则应首先使用Select查询来检查表中是否已存在'Nick' = $username ,如果不存在,则发出插入

Example

$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