How can I with mysqli make a query with LIKE and get all results?
Here's a quick code snippet to perform a LIKE
query and fetch all results using mysqli
. The '%wildcard is used to match any values in a
column`:
Prepared Statements for Secure Queries
Shoring up your defenses is important! Prepared statements help to prevent SQL injection. We use placeholders (?
) in SQL statements:
Using %
in the search term and not as a wildcard? Escape it:
Fetching Multiple Rows in One Go!
Why fetch one when you can fetch all? fetch_all(MYSQLI_ASSOC)
fetches all results at once in an associative array. Bigger result sets, here we come:
PHP 8.2 has your back with the execute_query
method for extra sleek code:
Combining Columns Efficiently with MySQL CONCAT
MySQL CONCAT()
in your LIKE
queries is a smart move when you need to search across combined columns:
Visualising Query Patterns
Imagine a library catalog system (📚):
It's like telling the librarian:
Result? A cornucopia of 'Harry':
Behold! LIKE '%Harry%'
. You'll find 'Harry' lurking in any nook and cranny of the title!
Escaping Wildcards with Regex Negative Lookahead
Search term with %
or _
not as wildcards but literal characters? It's important to escape them. Let's invite regex negative lookahead to the party:
Binding Result to Variables
bind_result
offers an alternative fetching method, binding results to variables:
Was this article helpful?