嘗試使用以下方法將值數組綁定到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中文網其他相關文章!