首頁 >資料庫 >mysql教程 >如何使用 mysqli 透過 LIKE 查詢檢索多行?

如何使用 mysqli 透過 LIKE 查詢檢索多行?

Patricia Arquette
Patricia Arquette原創
2025-01-20 06:21:101010瀏覽

How to Retrieve Multiple Rows with a LIKE Query Using mysqli?

MySQLi LIKE 查詢:檢索多行

提供的程式碼使用bind_resultfetch,僅適合單行檢索。 若要使用 MySQLi 取得與 LIKE 查詢相符的多行,請考慮以下方法:

方法一:使用get_result()

此方法傳回一個結果集對象,讓您可以使用 fetch_all() 將所有行作為關聯數組檢索:

<code class="language-php">$param = "%{$_POST['user']}%";
$stmt = $db->prepare("SELECT id, username FROM users WHERE username LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);</code>

方法 2:使用 execute_query()(PHP 8.2 及更高版本)

這種簡化的方法會同時執行查詢並取得所有結果:

<code class="language-php">$sql = "SELECT id, username FROM users WHERE username LIKE ?";
$result = $db->execute_query($sql, ["%{$_POST['user']}%"]);
$data = $result->fetch_all(MYSQLI_ASSOC);</code>

方法3:迭代fetch()

如果您喜歡 bind_result()fetch() 方法,請使用循環迭代多行:

<code class="language-php">$stmt = $db->prepare("SELECT id, username FROM users WHERE username LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($id, $username);
while ($stmt->fetch()) {
  echo "Id: {$id}, Username: {$username}";
}</code>

這些替代方法可以有效地檢索滿足您的 LIKE 條件的所有行。 選擇最適合您的程式設計風格和 PHP 版本的方法。

以上是如何使用 mysqli 透過 LIKE 查詢檢索多行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn