简体   繁体   中英

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.

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. 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.

Here is one way you can do this custom is_in_array function source

//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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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