根据拆分字符串的结果创建 MYSQL 查询并使用 LIKE 匹配 PHP 中的关键字
Creating a MYSQL query from results of splitting a string and using LIKE to match keywords in PHP
我正在尝试将一个字符串拆分成一个数组,并将它们用作关键字来进行 sql 查询。我做了一个拆分数组和构建 sql 查询的示例。它有点工作,但它给出了每个 table 结果,但是当我硬复制构建的查询时,它会得到预期的结果。
这是我目前所拥有的 -
将关键字字符串拆分成数组并构建查询。
数据库称为 'clients_personal',table 称为 'likes'
$my_search = "paper, glue, discount, bulk";
$new_search = preg_split("/,/", $my_search);
$mmsql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%'";
foreach ($new_search as $value) {
$mmsql = $mmsql." OR likes LIKE '%$value%'";
}
不,结果类似于:
$mmsql="SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
现在如果我这样搜索,我会得到数据库中的所有行吗?
$sql = "$mmsql";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id=$row["id"];
echo $id;
}
}
但是如果我的查询是硬编码的,它会给出预测结果吗?
$sql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
$result = $conn->query($sql);
我觉得它与引号有关,我尝试删除它们但没有用?有什么建议吗?
我也使用我在此处找到的这种类型的搜索。
问题出在这里$new_search = preg_split("/,/", $my_search);
请改用$new_search = preg_split("/, /", $my_search);
。
字符串中的项目由逗号和 space (", ") 分隔,因此您应该用逗号分隔字符串。
我正在尝试将一个字符串拆分成一个数组,并将它们用作关键字来进行 sql 查询。我做了一个拆分数组和构建 sql 查询的示例。它有点工作,但它给出了每个 table 结果,但是当我硬复制构建的查询时,它会得到预期的结果。
这是我目前所拥有的 -
将关键字字符串拆分成数组并构建查询。
数据库称为 'clients_personal',table 称为 'likes'
$my_search = "paper, glue, discount, bulk";
$new_search = preg_split("/,/", $my_search);
$mmsql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%'";
foreach ($new_search as $value) {
$mmsql = $mmsql." OR likes LIKE '%$value%'";
}
不,结果类似于:
$mmsql="SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
现在如果我这样搜索,我会得到数据库中的所有行吗?
$sql = "$mmsql";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id=$row["id"];
echo $id;
}
}
但是如果我的查询是硬编码的,它会给出预测结果吗?
$sql = "SELECT * FROM clients_personal WHERE likes LIKE '%offers%' OR likes LIKE '%paper%' OR likes LIKE '%glue%' OR likes LIKE '%discount%' OR likes LIKE '%bulk%'";
$result = $conn->query($sql);
我觉得它与引号有关,我尝试删除它们但没有用?有什么建议吗? 我也使用我在此处找到的这种类型的搜索。
问题出在这里$new_search = preg_split("/,/", $my_search);
请改用$new_search = preg_split("/, /", $my_search);
。
字符串中的项目由逗号和 space (", ") 分隔,因此您应该用逗号分隔字符串。