PHP PDO MySQL查询LIKE - >多个关键字

时间:2014-10-30 18:44:55

标签: php mysql search sql-like

我在MySQL中有一个用户表,希望按名称搜索。现在我有以下代码:

<?php
$search = @$_GET['q'];
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);

$query = $con->prepare('SELECT * FROM `users` WHERE name LIKE ?');
$query->execute(array('%'.$search.'%'));

$result = $query->rowCount();
echo $result;
?>

问题是我想拥有多个关键字。让我们说出某人的类型&#34;这里应该是一个好人的名字&#34;那么它会搜索&#34;这里&#34;,&#34;应该&#34;,&#34; be&#34;等等,并显示每个行中有单词的名称&#39;柱。我在网上搜索并读到可以做&#34;或者命名LIKE?&#34;与关键字一样多次,但我无法真正使用它,我不确定它是否已经足够大约20个单词(如果用这么多单词搜索的话)。如果应该使用它,你能帮我改变我的代码,以便它能独立搜索每个单词吗?

谢谢!

编辑:

我能够通过发布在这个帖子中的一个人解决这个问题。以下解决方案适用于我:

<?php
$search = isset($_POST['q']) ? $_POST['q'] : '';
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);

$split_words = explode(" ", $search);

if(count($split_words) > 0) {

    $sql = "SELECT * FROM `users` WHERE ";

    for($i=0 ; $i < count($split_words); $i++){
        $sql .= " name LIKE ? OR";
    }

    $sql = substr($sql , 0, -3); //Remove last 3 characters OR with space
    array_walk($split_words, "addPercentage");


    $query = $con->prepare($sql);
    $query->execute($split_words);
}

function addPercentage(&$value, $key) {
    $value = '%'.$value.'%';
}
?>

3 个答案:

答案 0 :(得分:3)

你不应该使用@来消除错误这是一个不好的做法,检查是否设置了值。下面的示例应该有效,但结果可能并非完全相关。

$search = isset($_GET['q']) ? $_GET['q'] : ''; 
$search = strtoupper($search);
$search = strip_tags($search); 
$search = trim($search);
$words = explode(' ', $search);
$words_condition = array();
$arguments = array();
foreach ($words as $word) {
    $words_condition[] = 'name LIKE ?';
    $arguments[] = '%'.$word.'%';
}

$query = $con->prepare('SELECT * FROM `users` WHERE '.implode(' OR ', $words_condition));
$query->execute($arguments);

$result = $query->rowCount();
echo $result;

答案 1 :(得分:0)

$words = explode(" ", $search);

$i = 0;
while($words[i] != null)
{
    //Query where name LIKE words[i]
}

答案 2 :(得分:0)

请检查以下代码。

<?php
$search = isset($_GET['q']) ? $_GET['q'] : '';
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);

$split_words = explode(" ", $search);

$query = "SELECT * FROM `users`";

if(count($split_words) > 0){
 $query .= " WHERE "
 for($i=0 ; $i < $split_words; $i++){
   $query .= " name LIKE ? OR ";
 }
 $query = substr($query , 0, -3); //Remove last 3 characters OR with space


 array_walk($split_words,"addPercentage");

 $query->execute($split_words);
}else{
 $query->execute();
}

$result = $query->rowCount();
echo $result;

function addPercentage(&$value,$key)
{
  $value = "%".$value."%" ;
}
?>