2017-03-12 74 views
0
try { 
    $keyword = trim($_GET["keyword"]); 
    if ($keyword <> "") { 
    $sql = "SELECT * FROM tbl_contacts WHERE 1 AND " 
      . " (first_name LIKE :keyword) ORDER BY first_name "; 
    $stmt = $DB->prepare($sql); 

    $stmt->bindValue(":keyword", $keyword."%"); 

    } else { 
    $sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name "; 
    $stmt = $DB->prepare($sql); 
    } 

我需要做多個搜索,以名字,姓氏,middle_name,contact_no1領域如何創建多個搜索?

+2

問題是什麼? – Rizier123

+0

在你的查詢中使用'OR'和多個bindValue – Roljhon

回答

0

如果你想要做搜索的所有字段WHERE添加字段與OR

try { 
    $keyword = trim($_GET["keyword"]); 
    if ($keyword <> "") { 
    $sql = "SELECT * FROM tbl_contacts WHERE 1 AND " 
      . " (first_name LIKE :keyword OR last_name LIKE :keyword OR middle_name LIKE :keyword OR contact_no1 LIKE :keyword) ORDER BY first_name "; 
    $stmt = $DB->prepare($sql); 

    $stmt->bindValue(":keyword", $keyword."%"); 

    } else { 
    $sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name "; 
    $stmt = $DB->prepare($sql); 
    } 
+0

哦))非常感謝)它的工作原理)) –

0
public function search($requestArray){ 
$sql = ""; 
if(isset($requestArray['firstname']) && isset($requestArray['lastname'])) $sql = "SELECT * FROM `tbl_contacts` WHERE AND (`first_name` LIKE '%".$requestArray['search']."%' OR `last_name` LIKE '%".$requestArray['search']."%')"; 
if(isset($requestArray['firstname']) && !isset($requestArray['lastname'])) $sql = "SELECT * FROM `tbl_contacts` WHERE `first_name` LIKE '%".$requestArray['search']."%'"; 
if(!isset($requestArray['firstname']) && isset($requestArray['lastname'])) $sql = "SELECT * FROM `tbl_contacts` WHERE `last_name` LIKE '%".$requestArray['search']."%'"; 

$STH = $this->DBH->query($sql); 
$STH->setFetchMode(PDO::FETCH_OBJ); 
$someData = $STH->fetchAll(); 

return $someData; 

} 

我在我的一個項目中使用這種方法尋找兩個領域希望它可以幫助你。 $ requestArray將從form和'firstname'中獲取數據,'lastname'是數組的兩個關鍵字,您將進入您的搜索框並提交搜索。我只是在這裏向你展示了查詢風格,並且在此之前你已經修改了這些值。