首页 >后端开发 >php教程 >如何将字符串数组绑定到 MySQLi WHERE IN 子句?

如何将字符串数组绑定到 MySQLi WHERE IN 子句?

Linda Hamilton
Linda Hamilton原创
2025-01-01 14:06:12523浏览

How to Bind an Array of Strings to a MySQLi WHERE IN Clause?

使用 MySQLi 准备语句在 WHERE IN 子句中绑定字符串数组

尝试使用以下方法将值数组绑定到 WHERE IN 子句时可能会遇到挑战MySQLi。一种常见的错误是错误地使用bind_param。以下是解决此问题的方法:

PHP 8.2 及更高版本: Execute_query()

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()

对于 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);

较旧的 PHP 版本:准备/绑定/执行

对于旧版本,请使用以下方法:

$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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn