How to implement a universal search filter in PHP OOP using MySQLi Prepared Statements and LIKE [closed]

17 hours ago 1
ARTICLE AD BOX

I am trying to implement a universal search bar using PHP OOP and MySQLi prepared statements. The goal is to filter a user list by name, email, or surname using a single search input.

The Problem: The query executes without errors, but it returns an empty array even when I search for terms that I know exist in the database.

My Code:

public function getUsers($filter = null) { // 1. Start with the basic query $sql = "SELECT * FROM user"; if ($filter !== null && $filter !== '') { $queryFilter = "%" . $filter . "%"; $sql .= " WHERE name LIKE ? OR email LIKE ? OR surname LIKE ?"; $stmt = $this->conn->prepare($sql); $stmt->bind_param("sss", $queryFilter, $queryFilter, $queryFilter); } else { $stmt = $this->conn->prepare($sql); } $stmt->execute(); return $stmt->get_result()->fetch_all(MYSQLI_ASSOC); }

My PHP

<?php require_once "User.php"; $userObj = new User(); // Grab 'search' from the URL (e.g. userList.php?search=Petr) $search = $_GET['search'] ?? null; $users = $userObj->getUsers($search); ?> <form method="GET"> <input type="text" name="search" placeholder="Search users..." value="<?= htmlspecialchars($search ?? '') ?>"> <button type="submit">Filter</button> <a href="userList.php">Reset</a> </form> <table border="1"> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <?php foreach ($users as $u): ?> <tr> <td><?= $u['name'] . " " . $u['surname'] ?></td> <td><?= $u['email'] ?></td> </tr> <?php endforeach; ?> </tbody> </table>

My HTML form.

Read Entire Article