簡體   English   中英

拆分字符串以放入CodeIgniter Active Record SQL查詢中

[英]Splitting a string to put into a CodeIgniter Active Record SQL query

我正在嘗試進行搜索查詢,以查看textarea是否包含一些關鍵字。 我將textarea的值插入查詢中時遇到了麻煩。

這是我的查詢:

$match = $this->input->post('wStory');
$this->db->where("`terms` LIKE '%$match%'");
$query = $this->db->get('filter_tbl');
return $query->num_rows();

$match是我的文本字段,我一直想做的是將里面的單詞分開,然后遍歷每個單詞。 我試過使用PHP的explode()函數進行某種工作,但是在這種情況下,它不起作用,因為它將字符串轉換為數組。

有什么方法可以將文本區域中的字符串拆分成單詞,然后遍歷like語句中的單詞?還是我缺少某些東西?

您當前正在運行的查詢正在檢查特定短語,而不是檢查任何指定的單詞。

您需要執行以下操作:

$match = $this->input->post('wStory');

// break search phrase into keywords
$keywords = explode(' ', $match);

// Build query
foreach ($keywords as $keyword)
{
    $keyword = trim($keyword);
    $this->db->or_where("`terms` LIKE '%$keyword%'");
}
$query = $this->db->get('filter_tbl');
return $query->num_rows();

explode(' ', $match)不考慮可能分隔單詞的任何標點符號。

是否沒有$this->db->like("terms", $match); 方法?

參見http://ellislab.com/codeigniter/user-guide/database/active_record.html#like

我認為全文搜索是必經之路。 Rob W發布的網址也給出了以下信息:

$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);

在您看來,這就像

$this->db->where('MATCH (terms) AGAINST ("$match")', NULL, FALSE);

編輯:進一步閱讀后,這可能會更好(或至少可讀性更好):

$this->db->where('MATCH (terms) AGAINST ("$match")');

嘗試這個:

$match = $this->input->post('wStory');

//Getting words from textarea and put them into array
$wordsArray = explode(' ',$match);

if (!empty($wordsArray)) {
    //use where_in() instead of where()
    $this->db->where_in("`terms`", $wordsArray);

    $query = $this->db->get('filter_tbl');
    return $query->num_rows();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM