Creating a php search bar

Creating a php search bar

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Filtering User Results by Search Query

To make a search bar functional, you need to shift from retrieving an entire dataset to executing a conditional query that filters results based on user input. The provided code snippet demonstrates a common starting point: a form submits a GET request to users.php, and the PHP script currently fetches every username in the member table without checking against the search term.

The core issue lies in how the SQL query is constructed inside the PHP script. Currently, the statement SELECT username FROM member ignores the data sent from the form. To fix this, you must capture the value from the $_GET['search'] superglobal variable and inject it into the SQL WHERE clause.

Capturing Input and Validating Safety

When a user types a name into the input field and clicks Search, the browser sends that string as part of the URL query string (e.g., users.php?search=John). In PHP, this value is available via $_GET['search'].

You must assign this variable before running your query. However, simply echoing the raw content directly into the SQL string or outputting it without checks is a critical security vulnerability known as SQL Injection. Attackers can manipulate the input to alter your database queries or exfiltrate data.

The legacy mysql_* functions used in your example are deprecated and removed in newer PHP versions because they lack built-in protection against these attacks. You should migrate to PDO (PHP Data Objects) or MySQLi with prepared statements. Prepared statements separate the SQL logic from the data, ensuring that user input is treated strictly as text, never as executable code.

Implementing the Filtered Query

Here is how you would refactor the logic using PDO to safely filter users:

<?php
// Establish a secure connection using PDO
$dsn = 'mysql:host=localhost;dbname=blog1;charset=utf8mb4';
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, 'root', '', $options);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

// Capture the search term
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';

if (!empty($searchTerm)) {
    // Use a prepared statement to safely filter results
    $stmt = $pdo->prepare("SELECT username FROM member WHERE username LIKE :keyword");
    
    // The % wildcards allow for partial matches (e.g., "ohn" finds "John" and "Johnson")
    $searchPattern = "%{$searchTerm}%";
    
    $stmt->execute(['keyword' => $searchPattern]);
    
    $results = $stmt->fetchAll();

    if (!empty($results)) {
        foreach ($results as $row) {
            // Escape output for HTML contexts to prevent XSS
            echo '<div id="link" onclick="addText(\'' . htmlspecialchars($row['username']) . '\');">' 
                . $row['username'] . '</div>';
        }
    } else {
        echo 'No users found matching "' . htmlspecialchars($searchTerm) . '".';
    }
} else {
    // Fallback to showing all users if no search term is provided
    $stmt = $pdo->query("SELECT username FROM member");
    $results = $stmt->fetchAll();

    foreach ($results as $row) {
        echo '<div id="link" onclick="addText(\'' . htmlspecialchars($row['username']) . '\');">' 
            . $row['username'] . '</div>';
    }
}
?>

Handling Case Insensitivity and Partial Matches

Your original code uses a simple SELECT statement. If you want the search to be forgiving—allowing users to type "john" to find "John"—you should use SQL wildcards (%) combined with the LOWER() function or rely on the database's default collation settings if case-insensitivity is desired out of the box. The example above uses %{$searchTerm}%, which matches any username containing the typed substring regardless of position.

Addressing Security and Modern Standards

The original code relies on mysql_connect and mysql_query. These functions were deprecated in PHP 5.5 and removed entirely in PHP 7.0. Continuing to use them will prevent your application from running on modern servers. The transition to PDO is not just about fixing syntax; it is about adopting a standard that supports prepared statements, which are the industry requirement for handling dynamic user input.

Additionally, notice the output generation in the code examples. When generating HTML elements based on user input, you must use htmlspecialchars() to escape special characters like quotes and angle brackets. Without this, a malicious user could inject JavaScript code (XSS) into your page simply by typing a name that includes script tags.

If you are building larger applications or need more advanced features like pagination, caching results, or integrating with complex routing, consider leveraging the Laravel framework. Laravel provides robust tools for handling database queries and form validation securely out of the box. For more details on modern PHP development practices and secure coding standards, you can explore resources such as https://laravelcompany.com.

Our network