Home > Database > Mysql Tutorial > How to Properly Fetch Multiple Search Results Using LIKE in MySQLi?

How to Properly Fetch Multiple Search Results Using LIKE in MySQLi?

Mary-Kate Olsen
Release: 2025-01-20 06:17:13
Original
985 people have browsed it

How to Properly Fetch Multiple Search Results Using LIKE in MySQLi?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template