我希望PHP使用MySQLi和bind_param()
如果搜索字符串为some word
,则PHP搜索some
和word
我找到了这个答案
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();
}
答案 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();
}