Home >Database >Mysql Tutorial >How to Fetch All Results from a MySQLi LIKE Query?

How to Fetch All Results from a MySQLi LIKE Query?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-20 06:02:09738browse

How to Fetch All Results from a MySQLi LIKE Query?

Retrieving Multiple Records from MySQLi LIKE Queries

MySQLi's LIKE queries can yield multiple results. However, the standard fetch() method only retrieves the first row. This guide outlines several ways to fetch all matching records.

Method 1: get_result() and fetch_all()

This is the preferred method. get_result() fetches the entire result set, and fetch_all() efficiently converts it into an associative array:

<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>

Method 2: Prepared Statements with fetch() and Looping

This approach utilizes prepared statements with bind_result() and iterates using fetch() until no more rows are available:

<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()) {
  // Process each row ($id, $username)
}</code>

Method 3: execute_query() (PHP 8.2 and later)

For PHP 8.2 and above, execute_query() provides a concise alternative:

<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>

Helpful Resources:

The above is the detailed content of How to Fetch All Results from a MySQLi LIKE Query?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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