使用PHP搜索搜索字符串中的每个单词mysqli bind_param()

时间:2019-04-18 13:01:32

标签: php mysqli

我希望PHP使用MySQLi和bind_param()

在MySQL数据库中搜索字符串中的每个单词。

如果搜索字符串为some word,则PHP搜索someword

我找到了这个答案 Search Each Word Of a Search Using PHP MYSQL Search Query 但我不能将其与MySQLi和bind_param()

一起使用

这是我的代码:

if (!empty($search)) {
    $search = "%{$search}%";
    $sql = $conn->prepare("SELECT * FROM `hospitals` WHERE hospname LIKE ?");
    $sql->bind_param("s",$search);
    $sql->execute();
    $result = $sql->get_result();
    $sql->close();
}

2 个答案:

答案 0 :(得分:2)

更清洁的解决方案

$search_arr = explode(" ",$search);
$params = [];
$where = [];

foreach($search_arr as $word)
{
    $where[] = "hospname like ?";
    $params[] = "%$word%";
}
$query = "SELECT * FROM `hospitals` WHERE ".implode($where, " or ");
$sql = $conn->prepare($query);

$sql->bind_param(str_repeat('s', count($params)), ...$params);
$sql->execute();

$result = $sql->get_result();

答案 1 :(得分:0)

这可能有帮助

if (!empty($search)) {
$search = explode(" ",$search);


$query="SELECT * FROM `hospitals` WHERE hospname";
$params=array();
$params_type="";

foreach($search as $word)
{

    $query.=" like ? or hospname";
    $params_type.='s';

}

$params[]=& $params_type;

$query=rtrim($query, 'or hospname');
$sql = $conn->prepare($query);




foreach($search as $word)
{

    $search_word="%{$word}%";
    $params[]=& $search_word;

}
call_user_func_array(array($sql,'bind_param'), $params);
$sql->execute();

$result = $sql->get_result();

}