John Davidson

javascript - Checkbox filters on search results with strictly PHP?

0 comments
Message:


I'm creating a basic book review page for a class I'm currently taking. I've been able to accomplish simple searches from my Database:


$search_request = "SELECT * 
FROM books
WHERE author
LIKE '%$searchfor%' COLLATE UTF8_GENERAL_CI
OR title LIKE '%$searchfor%' COLLATE UTF8_GENERAL_CI";

This results in a perfectly fine request and answer.


However, this just provides me with a list of the books. I would like to filter the search results.


Say someone searches "Tolkien", then I would like to have two checkboxes: Authors and Books, where they could filter the Tolkien search to display authors named Tolkien or Books including Tolkien.


As long as I have some way of recieving a input which indicates either author and books, I will have no problem writing up the sql query to achieve it.


I've tried with both $_GET through an anchor and $_POST with an additional form, however the GET and the POST overwrite my existing POST with the initial search. Is there a way to do this strictly with PHP or very simple JS?



My Answer:
One way to achieve this is to use JavaScript to handle the checkbox filters on the search results page. Here's an example of how you can do this:

1. Add checkboxes for Authors and Books in your HTML form:

html


Authors
Books




2. Modify your PHP code to handle the checkbox filters:

php
$searchfor = $_POST['searchfor'];
$filters = isset($_POST['filter']) ? $_POST['filter'] : array();

$search_request = "SELECT * FROM books WHERE ";

if (in_array('author', $filters)) {
$search_request .= "author LIKE '%$searchfor%' COLLATE UTF8_GENERAL_CI";
}

if (in_array('book', $filters)) {
if (in_array('author', $filters)) {
$search_request .= " OR ";
}
$search_request .= "title LIKE '%$searchfor%' COLLATE UTF8_GENERAL_CI";
}

// Execute the SQL query and display the search results


3. Use JavaScript to submit the form when the checkboxes are checked/unchecked:

javascript
document.querySelectorAll('input[type="checkbox"]').forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
document.querySelector('form').submit();
});
});


With this setup, when the user enters a search term and checks the checkboxes for Authors and/or Books, the form will be submitted with the selected filters. The PHP code will then generate the appropriate SQL query based on the selected filters.

Rate this post

3 of 5 based on 8169 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us