2016-03-29 105 views
1
<?$search=$_POST['search']; 
$query = $pdo->prepare("select * from tag where tag1 LIKE '%$search%' OR tag2 LIKE '%$search%' LIMIT 0 , 10"); 
$query->bindValue(1, "%$search%", PDO::PARAM_STR); 
$query->execute(); 
// Display search result 
     if (!$query->rowCount() == 0) { 
       echo "Search found :<br/>"; 

      while ($results = $query->fetch()) { 

       echo "$".$results['name']; 
       echo "</td></tr>";    
      } 
       echo "</table>";   
     } else { 
      echo 'Nothing found'; 
     } 
?> 
<form action="" method="post"> 
Search: <input type="text" name="search" placeholder=" Search here ... "/> 
<input type="submit" value="Submit" /> 
</form> 

我知道這裏有很多類似的問題,但我仍然無法弄清楚。如果有人有時間,請解釋我如何在我的搜索中添加explode,以便我可以使用多於1個單詞進行搜索? 非常感謝您的時間。 如果我在我的標記中輸入1個單詞,該腳本會執行搜索。但是如果我輸入2個單詞,它將返回0個結果。PHP MYSQL多字搜索

+0

爆炸由分離器 – RomanPerekhrest

+1

的SQL注入風險高搜索字符串:'$搜索= '%' $搜索 '%';。 $ query = $ pdo-> prepare(「select * from tag where tag1 LIKE:strings OR tag2 LIKE:strings LIMIT 0,10」); $ query-> bindParam(':strings',$ search,PDO :: PARAM_STR);' – aldanux

+0

正如僅供參考,您對***注入不是安全的。通過在這裏嵌入用戶輸入:'%$ search%',您允許直接用戶操縱您的SQL語句。你使用'bindValue'是不正確的。考慮改變你的語句,如下所示:'$ query = $ pdo-> prepare(「select * from tag where tag1 LIKE'%:search1%'or tag2 LIKE'%:search2%'LIMIT 0,10」); $ query-> bindValue(「:search1」,$ search,PDO :: PARAM_STR); $ query-> bindValue(「:search2」,$ search,PDO :: PARAM_STR);' – War10ck

回答

2

注意什麼上bindValue的文件說,關於第一個參數:

參數標識。

對於使用命名佔位符的準備語句,這將是:name形式的參數名稱。對於使用問號佔位符的準備好的語句,這將是參數的1索引位置。

在您的SQL字符串中既沒有?佔位符,也沒有冒號前綴的命名佔位符。實際上,您實際上是直接在SQL中注入用戶提供的輸入,並且對於SQL注入而言容易受到攻擊。 因此,您應該按照文檔中所述開始使用佔位符。

如果您想要找到任何單獨的單詞,那麼您需要動態擴展您的WHERE ,爲每個單詞匹配添加OR-條件。在這樣的動態生成的SQL中使用?佔位符 會更容易。

而且,由於你的論點是字符串,您可以使用execute可選參數來傳遞參數數組:

input_parameters

值的陣列一樣多的元素有是正在執行的SQL語句中的綁定參數。所有的值都被視爲PDO::PARAM_STR

下面是一些建議代碼:

// Explode to words and filter for words which are not the empty string: 
$words = array_filter(explode(" ", $_POST['search']), 'strlen'); 
// Wrap each of the words in '%' 
$words = array_map(function ($search) { return "%$search%"; }, $words); 
// Add a condition for each of the words in the WHERE clause, and repeat for tag2 
$sql = "select * 
     from tag 
     where " . 
     implode(" OR ", array_fill(0, count($words), "tag1 LIKE ?")) . 
     " OR " . 
     implode(" OR ", array_fill(0, count($words), "tag2 LIKE ?")) . 
     " LIMIT 0, 10";  
$query = $pdo->prepare($sql); 
// Pass the values as string twice: once for tag1 and once for tag2 
$query->execute(array_merge($words, $words));