Topics Covered in This PHP & MySQL Tutorial:
Wildcard Searches, Searching with a Form
Exercise Overview
Database search functionality forms the backbone of modern web applications—from e-commerce product catalogs to customer management systems. While there are countless sophisticated search techniques available, mastering wildcard searches provides the fundamental building blocks for more advanced implementations. In this exercise, we'll build a robust search interface that demonstrates how to safely perform wildcard queries using parameterized statements, ensuring both functionality and security.
This tutorial covers basic wildcard searching on a single column. Database search capabilities extend far beyond this foundation, including full-text search, multiple column searches, and advanced filtering techniques.
Tutorial Workflow
Examine Search Form
Review the HTML form structure in search.php that captures user email input
Implement SQL Query
Add LIKE operator with wildcards to filter database results effectively
Process User Input
Modify search terms with percent signs for wildcard functionality
Bind Parameters
Secure the query by properly binding the search term parameter
Simple Search
The foundation of any wildcard search lies in the SQL LIKE operator combined with strategic wildcard placement. To search for a user by email, the syntax would be:
SELECT *
FROM users
WHERE email LIKE '%mySearchTerm%'
This query will match any record in the database where the email field contains the specified search term. The % wildcard characters on either side create a flexible pattern that matches any text before or after the user's input. For example, searching for "john" would return emails like "john.doe@company.com", "johnny@example.org", or "info@johnsonlaw.net".
Now let's implement this search functionality through a practical, hands-on approach:
Open search.php from the search folder.
In your browser, navigate to the search interface:
- Mac: localhost:8888/phpclass/search/search.php
- Windows: localhost/phpclass/search/search.php
You'll see a streamlined search form with a single email input field. This form submits to searchResults.php, which handles the database query and displays matching results in a formatted table.
Return to your code editor to examine the backend implementation.
Open searchResults.php from the search folder.
The foundational structure is already in place—including database connection, SELECT statement, and result output formatting. Our task is to enhance this with wildcard functionality and ensure the user input is properly sanitized for the parameterized query.
Locate line 5 and modify the $SQL variable by adding the highlighted WHERE clause:
$SQL = 'SELECT id, firstName, lastName, email, publications, comments, subscribe FROM users WHERE email LIKE ? ';This modification transforms our query from selecting all records to filtering results based on email pattern matching using the LIKE operator with a parameterized placeholder.
SELECT * FROM users WHERE email LIKE '%mySearchTerm%'Wildcard Pattern Breakdown
Leading Wildcard (%)
Matches any characters before the search term. Enables finding emails ending with specific patterns.
Search Term
The actual text users enter. Can be partial email addresses, domains, or any text fragment.
Trailing Wildcard (%)
Matches any characters after the search term. Allows finding emails starting with specific patterns.
File Setup Requirements
Contains the HTML form for user input
Test the form interface before backend implementation
Where you'll implement the search logic and display results
Foundation code is already provided for modification
Modifying the Search Term
Here's where many developers encounter a crucial implementation detail: wildcard characters cannot be embedded directly within the SQL query when using parameterized statements. Instead, we must append the percent signs to the search term itself before binding the parameter. This approach maintains the security benefits of parameterized queries while enabling flexible pattern matching.
Create the wildcard-enabled search term by concatenating percent signs to the form input. Add this code above the $SQL variable declaration:
$searchTerm = '%'. $_POST['email']. '%';This line captures the email value submitted from the form (
$_POST['email']) and wraps it with wildcard characters, creating a flexible search pattern that matches partial email addresses.Complete the implementation by binding the search parameter to the prepared statement. Around line 14, locate the //bind params here comment and replace it with:
$stmt->bind_param('s', $searchTerm);This critical step binds our
$searchTermvariable to the query placeholder, with the 's' parameter indicating we're passing a string value. This approach prevents SQL injection attacks while maintaining search flexibility.Save your changes and test the implementation by returning to your browser:
- Mac: localhost:8888/phpclass/search/search.php
- Windows: localhost/phpclass/search/search.php
Experiment with both complete and partial email addresses to verify the wildcard functionality works as expected. Try searching for domain names, usernames, or partial matches to see the full power of your implementation.
Return to your code editor to review the completed functionality.
Close any open files. You've successfully implemented a secure, flexible wildcard search system!
PHP doesn't allow percent signs directly in SQL queries for security reasons. The wildcards must be concatenated to the search term variable instead of embedded in the SQL string.
$searchTerm = '%'. $_POST['email']. '%';Parameter Binding Implementation
Add LIKE Operator
Modify SQL variable around line 5 to include WHERE email LIKE ? clause
Concatenate Wildcards
Create searchTerm variable by adding % signs before and after POST email value
Bind Search Parameter
Replace comment at line 14 with bind_param function specifying string type
Test Search Functionality
Save files and test with full or partial email addresses in browser