簡體   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