2014-09-23 50 views
0

我正在嘗試使用php和MySQL來執行搜索功能。我需要從兩個不同的列,一爲歌曲名稱和一個藝術家和用戶搜索可以使用搜索:php MySQL搜索兩列

1. artist name. 
2. song title. 
3. both of them (without order) 
4. there will be special characters for ex: ' (apostrophe) 

這是我做了什麼,但我需要一個更有效的方式來做到這一點。我也曾想過在php中使用similar_text();。任何人都可以建議我一個更好的方法來做到這一點謝謝

表:songs

|artist | title | 
|----------------------| 
|eminem | not afraid | 
|kida  | o'najr  | 

我的代碼:

$search_value = $_POST["search_value"]; 
$query = "select * from `songs` where concat(`title`, `artist`) like '%$search_value%'"; 
+1

是否有沒有按什麼不工作?你有沒有想到的任何錯誤? – 2014-09-23 18:31:52

+1

這看起來恐怖不安全。你確定**你的用戶參數是[妥善轉義](http://bobby-tables.com/php)? '$ _POST'數據**從不**直接進入查詢。沒有以某種形式逃脫,這是行不通的。 – tadman 2014-09-23 18:33:53

+1

它的工作原理,但你知道...這不是一個很好的解決方案。也爲前例。它不應該與字符串的一部分一起工作。例如。如果你搜索:raid它顯示阿姆 - 不害怕的結果。這不應該發生。 – 2014-09-23 18:35:46

回答

1
  1. 您應該使用SQL語句OR,優於CONCAT一個在這種情況下。

  2. 結合你搜索前後的空間,這應該會給你預期的結果! (我的意思是,如果你搜索'raid',你不會找到'Eminem - 不怕',如果你想找到它,你必須搜索'怕'爲例;如果你想按照目的排序結果,你將不得不創建索引和使用它們,或使用Levenshtein方法或其他東西...)

  3. 不要忘記在sql語句中使用它之前逃避你的數據。

順便說一句,如果你想使它情況insesitive你將不得不使用blabla COLLATE UTF8_GENERAL_CI LIKE %what you search% blabla

// if you are using mysql_connect() 
$search_value = ' '.mysql_real_escape_string($_POST["search_value"]).' '; 
$query = "select * from `songs` where `title` like '%$search_value%' or `artist` like '%$search_value%'"; 

// if you are using PDO 
$args[':search_value'] = '% '.$_POST["search_value"].' %'; 

$query = "SELECT * FROM `songs` WHERE `title` LIKE :search_value OR `artist` LIKE :search_value"; 

$qry = $PDO->prepare($query); 
$res = $qry->execute($args); 

對於多關鍵詞搜索,你也可以使用

// for mysql_connect() 
$search_value = $_POST["search_value"]; 
$search_value = explode(' ', $search_value); 
foreach($search_value as $k => $v){ 
    $search_value[$k] = mysql_real_escape_string($v); 
} 
$search_value = ' '.implode(' % ', $search_value).' '; 

// for PDO 
$search_value = explode(' ', $_POST["search_value"]); 
$search_value = implode(' % ', $search_value); 
$args[':search_value'] = '% '.$search_value.' %'; 
1

您可以簡單地使用SQL語句或如果你不想混淆。

$search_value = $_POST["search_value"];//check user input first than create a query. 
$query = "select * from `songs` where `title` like '%$search_value%' or `artist` like '%$search_value%'";