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:
Prepare the Query:
$param = "%{$_POST['user']}%"; $stmt = $db->prepare("SELECT id, username FROM users WHERE username LIKE ?");
Bind Parameters:
$stmt->bind_param("s", $param);
Execute the Query:
$stmt->execute();
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; }
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!