首頁 >後端開發 >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