尝试使用以下方法将值数组绑定到 WHERE IN 子句时可能会遇到挑战MySQLi。一种常见的错误是错误地使用bind_param。以下是解决此问题的方法:
PHP 8.2 引入了execute_query() 函数,这使得使用多个执行准备好的语句变得简单
示例:
$mysqli = new mysqli("localhost", "root", "root", "db"); $array = ['Nashville','Knoxville']; $parameters = str_repeat('?,', count($array) - 1) . '?'; $sql = "SELECT name FROM table WHERE city IN ($parameters)"; $result = $mysqli->execute_query($sql, $array); $data = $result->fetch_all(MYSQLI_ASSOC);
对于 PHP 8.1,您可以将数组直接传递给execute():
$mysqli = new mysqli("localhost", "root", "root", "db"); $array = ['Nashville','Knoxville']; $sql = "SELECT name FROM table WHERE city IN (".str_repeat('?,', count($array) - 1) . '?)'; $stmt = $mysqli->prepare($sql); $stmt->execute($array); $result = $stmt->get_result(); $data = $result->fetch_all(MYSQLI_ASSOC);
对于旧版本,请使用以下方法:
$mysqli = new mysqli("localhost", "root", "root", "db"); $array = ['Nashville','Knoxville']; $in = str_repeat('?,', count($array) - 1) . '?'; $sql = "SELECT name FROM table WHERE city IN ($in)"; $types = str_repeat('s', count($array)); $stmt = $mysqli->prepare($sql); $stmt->bind_param($types, ...$array); $stmt->execute(); $result = $stmt->get_result(); $data = $result->fetch_all(MYSQLI_ASSOC);
以上是如何将字符串数组绑定到 MySQLi WHERE IN 子句?的详细内容。更多信息请关注PHP中文网其他相关文章!