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
Mary-Kate OlsenOriginal
2024-12-13 15:44:13783browse

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 ?");
  2. Bind Parameters:

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

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

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

    Prior to PHP 8.2:

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

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

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!

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