2016-05-11 227 views
0

我正在嘗試構建邏輯以創建與PDO一起使用的多字LIKE語句。構建多字LIKE爲PDO查詢準備的語句

這需要搜索字符串$海峽建狀部分的多個部分:

$str = $_POST['str']; 

$keywords = preg_split('/[\s]+/', $str); 
$totalKeywords = count($keywords); 

$search = "%$str%"; 
$sql_str = " AND post_content LIKE :search0 "; 

for($i=1 ; $i < $totalKeywords; $i++){ 
    $search_bit = ":search" . $i; 
    $sql_str .= " AND post_content LIKE $search_bit "; 
} 

這是SQL語句 - 與$ sql_str開槽到正確的點:

$sql = "SELECT d.ID 
      , d.post_date 
      , d.post_content 
      , d.post_cat_id 
      , d.post_label 
      , c.fld_cat 
      FROM tbl_log_days d 
      , tbl_log_cats c 
     WHERE d.post_cat_id = c.fld_id " . $sql_str . " 
     ORDER BY post_date"; 

然後爲綁定變量,我試了兩種方法:

$stmt = $pdo->prepare($sql); 

if (!empty($sql_str)) { 

    foreach ($keywords as $key => &$keyword){ 
     $foo = '%'.$keyword.'%'; 
     $stmt->bindParam(':search' . $key, $foo); 
    } 

} 

而且還(在foreach行中的$關鍵字之前沒有&符號):

$stmt = $pdo->prepare($sql); 

if (!empty($sql_str)) { 

    foreach ($keywords as $key => $keyword){ 
     $foo = '%'.$keyword.'%'; 
     $stmt->bindParam(':search' . $key, $foo); 
    } 

} 

但是,當我搜索例如「過去的山」,檢查是否實際運行產生的SQL(我能在MySQL查詢日誌記錄),只需要在搜索字符串中的最後一個字:

SELECT d.ID 
    , d.post_date 
    , d.post_content 
    , d.post_cat_id 
    , d.post_label 
    , c.fld_cat 
    FROM tbl_log_days d 
    , tbl_log_cats c 
WHERE d.post_cat_id = c.fld_id AND post_content LIKE '%past%' AND post_content LIKE '%past%' 
    ORDER BY post_date 

我也做了$關鍵字變量的的var_dump當運行搜索和它返回:

string(4) "hill" 
string(4) "past" 

我不能工作這一個。是否有可能做我想做的事情?

回答

0

我會做這樣的事情

for($i=1 ; $i < $totalKeywords; $i++){ 
    $search_num = "search" . $i; 
    $search_bit = ":" . $search_num; 
    $sql_str .= " AND post_content LIKE $search_bit "; 
    $foo = '%'.$keyword.'%'; 
    $V[$search_bit] = $foo; 
} 

$query = $pdo->prepare($sql); 
$query->execute($V); 

(我沒有測試此代碼,所以請原諒錯別字。)