Are there better practices for handling dynamic search and filter functions in PHP PDO queries?
When handling dynamic search and filter functions in PHP PDO queries, it is important to use prepared statements to prevent SQL injection attacks. One common approach is to dynamically build the SQL query based on the user input for search and filter criteria. This can be achieved by using conditional statements to append the necessary WHERE clauses to the query.
// Example of handling dynamic search and filter functions in PHP PDO queries
// User input for search and filter criteria
$searchKeyword = $_POST['search'];
$filterCategory = $_POST['category'];
// Base SQL query
$sql = "SELECT * FROM products WHERE 1";
// Array to store conditions for the WHERE clause
$conditions = array();
// Add search keyword condition
if (!empty($searchKeyword)) {
$conditions[] = "product_name LIKE :searchKeyword";
}
// Add filter category condition
if (!empty($filterCategory)) {
$conditions[] = "category = :filterCategory";
}
// Append conditions to the SQL query
if (!empty($conditions)) {
$sql .= " AND " . implode(" AND ", $conditions);
}
// Prepare and execute the PDO query
$stmt = $pdo->prepare($sql);
// Bind parameters
if (!empty($searchKeyword)) {
$stmt->bindValue(':searchKeyword', "%$searchKeyword%", PDO::PARAM_STR);
}
if (!empty($filterCategory)) {
$stmt->bindValue(':filterCategory', $filterCategory, PDO::PARAM_STR);
}
// Execute the query
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll();
Keywords
Related Questions
- What are the key principles of object-oriented programming (OOP) that should be understood before working with classes and inheritance in PHP?
- What is the correct syntax for handling checkbox values in PHP to avoid parse errors?
- How does cURL differ from other methods of communication with a server in PHP?