2013-07-08 137 views
-1

我試圖將以下MYSQL查詢轉換爲PDO語句與準備和執行功能,但因爲我是新的PDO我不知道,我怎麼能將它轉換爲PDO聲明!有任何想法嗎?有條件搜索與PDO

$db = new PDO('mysql:dbname=MYDBNAME;host=MYHOST', 'USERNAME', 'PASSWORD'); 

$searchName = $db->quote($_GET["searchstr"]); 

$searchTerms = explode(' ', $searchName); 
$searchTermBits = array(); 

foreach ($searchTerms as $term) 
{ 
    $term = trim($term); 
    if (!empty($term)) 
      $searchTermBits[] = "f_name LIKE '%$term%' OR l_name LIKE '%$term%'"; 
    else 
      $searchTermBits[] = "f_name = '$term'"; 
} 

$mysqlResult = $db->query("SELECT * FROM food_tbl WHERE (" . implode(' OR ', $searchTermBits) . ") AND country_id = 1 ORDER BY id DESC;"); 
+0

查看文檔:http://php.net/manual/de/book.pdo.php – luk2302

+0

@ luk2302我知道如何使用'PDO',我的主要問題是我無法轉換上面的搜索查詢到'PDO'語句查詢。 – iSun

+0

您的代碼段中沒有PDO代碼,請提供您已有的PDO代碼,以便我們改進。 – luk2302

回答

2
// sanitize and build the searchTerms from the incoming `searchstr` 
$searchTerms = !empty($_GET['searchstr']) 
      ? explode(' ', $_GET['searchTerms']) 
      : array(); 

// setup a dynamic list of arguments being passed in 
$where = array(); 
$params = array(); 
foreach ($searchTerms as $term) { 
    $term = trim($term); 
    if (!empty($term){ 
    $where[] = 'l_name LIKE ?'; 
    $params[] = $term; 
    } 
    $where[] = 'f_name ' . (empty($term) ? '=' : 'LIKE') . ' ?'; 
    $params[] = $term; 
} 

// establish a new PDO object 
$db = new PDO('...'); 

// prepare your query statement using the "static" query and a compiled 
// query built from the above loop. 
$query = $db->prepare('SELECT * ' 
        . 'FROM  food_tbl ' 
        . 'WHERE country_id = 1 ' 
        . ' AND (' . implode(' OR ', $where) . ') ' 
        . 'ORDER BY id DESC'); 
// pass in the list of parameters from the above loop to the prepared 
// statement and return the result 
$result = $query->execute($params); 

/* Work with $result */ 

可以動態填充$where$params爲1:1參數到值列表,然後從列表$where建立您的查詢,並通過在匹配$params列表。

我建議節省開了一個變量的實際查詢它傳遞給$db->prepare()echo/var_dump它(與$params一起)之前,所以你可以看到什麼是被移交給了PDO。有時候,一張圖片勝過1000個單詞,並且可視化它使它不像一個黑盒子,更容易理解。

+0

謝謝,但它什麼也沒有返回,下面是來自var_dump的SQL:'object(PDOStatement)#5(1){[「queryString」] => string(152)「SELECT * FROM food_tbl WHERE country_id = 1 AND(f_name LIKE? OR l_name LIKE?)ORDER BY id DESC;「} – iSun

+0

@iSun:看起來正確。那麼'$ params'數組呢? –

+0

通過在'$ params'數組中添加%來完成。 – iSun