Use MySQLi’s LIKE statement to efficiently obtain multiple search results
This article explores how to use MySQLi to get multiple results from a LIKE query.
The original code provided in the question attempts to get a single row of results, but this is not suitable for scenarios where multiple rows may be returned. To get all results correctly you can use:
<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>
Alternatively, starting with PHP 8.2, you can use the following more concise code:
<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>
If you prefer the traditional fetch
and bind_result
syntax, you can use the following code:
<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(); $stmt->bind_result($id, $username); while ($stmt->fetch()) { echo "Id: {$id}, Username: {$username}"; }</code>
These updated code snippets ensure that all matching rows are retrieved from the database, allowing you to access the data as needed.
The above is the detailed content of How to Properly Fetch Multiple Search Results Using LIKE in MySQLi?. For more information, please follow other related articles on the PHP Chinese website!