mySQL 结合 WHERE IN (?,?,?,..) 子句与 %?%
mySQL combine WHERE IN (?,?,?,..) clause with %?%
如何在 stmt 查询中创建结合 WHERE IN (?,?,?,..) 子句和 %?%(通常与 LIKE 运算符一起使用)的查询?
在下面的代码中,我尝试执行类似的查询:
SELECT * FROM `items` WHERE `name` IN (%?%, %?%, %?% )
MySQL table(项目):
================
| name |
================
| google pixel |
----------------
| iphone 9, iphone 10, iphone 11 |
----------------
| windows phone |
PHP :
$array = array("pixel" => 1, "iphone 10" => 2);
$placeholders = array_fill(0, count($array), '?');
$keys = $values = array();
foreach($array as $key => $value) {
$keys[] = "%".$key."%"; //<- here
$values[] = !empty($value) ? $value : null;
}
$query = "SELECT * FROM `items` WHERE `name` IN (".implode(',', $placeholders).")";
$stmt = $mysqli->prepare($query);
call_user_func_array(
array($stmt, 'bind_param'),
array_merge(
array(str_repeat('s', count($keys))),
$keys
)
);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$items[$row['name']] = $row;
}
$result->free();
echo "<pre>"; print_r($items);echo"</pre>";
Nigel 的解决方案有效。我通过 :
更改查询
$query = "SELECT * FROM `items` WHERE `name` LIKE ".implode(' OR `name` LIKE ', $placeholders);
如何在 stmt 查询中创建结合 WHERE IN (?,?,?,..) 子句和 %?%(通常与 LIKE 运算符一起使用)的查询?
在下面的代码中,我尝试执行类似的查询:
SELECT * FROM `items` WHERE `name` IN (%?%, %?%, %?% )
MySQL table(项目):
================
| name |
================
| google pixel |
----------------
| iphone 9, iphone 10, iphone 11 |
----------------
| windows phone |
PHP :
$array = array("pixel" => 1, "iphone 10" => 2);
$placeholders = array_fill(0, count($array), '?');
$keys = $values = array();
foreach($array as $key => $value) {
$keys[] = "%".$key."%"; //<- here
$values[] = !empty($value) ? $value : null;
}
$query = "SELECT * FROM `items` WHERE `name` IN (".implode(',', $placeholders).")";
$stmt = $mysqli->prepare($query);
call_user_func_array(
array($stmt, 'bind_param'),
array_merge(
array(str_repeat('s', count($keys))),
$keys
)
);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$items[$row['name']] = $row;
}
$result->free();
echo "<pre>"; print_r($items);echo"</pre>";
Nigel 的解决方案有效。我通过 :
更改查询$query = "SELECT * FROM `items` WHERE `name` LIKE ".implode(' OR `name` LIKE ', $placeholders);