Home > Backend Development > PHP Tutorial > How Can I Efficiently Retrieve Multiple Results from a MySQL LIKE Query Using mysqli?

How Can I Efficiently Retrieve Multiple Results from a MySQL LIKE Query Using mysqli?

Mary-Kate Olsen
Release: 2024-12-13 15:44:13
Original
781 people have browsed it

How Can I Efficiently Retrieve Multiple Results from a MySQL LIKE Query Using mysqli?

Querying with LIKE and Retrieving Multiple Results in mysqli

The code provided in the question, attempting to perform a LIKE query and fetch multiple results, encounters issues. The following steps outline the correct approach:

  1. Prepare the Query:

    $param = "%{$_POST['user']}%";
    $stmt = $db->prepare("SELECT id, username FROM users WHERE username LIKE ?");
    Copy after login
  2. Bind Parameters:

    $stmt->bind_param("s", $param);
    Copy after login
  3. Execute the Query:

    $stmt->execute();
    Copy after login
  4. Fetch the Results as an Array:
    From PHP 8.2 onwards:

    $result = $stmt->get_result();
    $data = $result->fetch_all(MYSQLI_ASSOC);
    Copy after login

    Prior to PHP 8.2:

    $result = $stmt->store_result();
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    Copy after login
  5. Alternatively, Fetch Results Incrementally:

    $stmt->bind_result($id, $username);
    while ($stmt->fetch()) {
        echo "Id: $id, Username: $username";
    }
    Copy after login

This revised code ensures that all matching results are retrieved, even if multiple rows are returned. The references provided in the answer further explain the techniques used.

The above is the detailed content of How Can I Efficiently Retrieve Multiple Results from a MySQL LIKE Query Using 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