Tuesday, 28 August 2018

Mysql does not return the expected results

This question already has an answer here:

  • Combine PHP prepared statments with LIKE 5 answers
I've tried so many different variations of this, I can't figure out why this isn't returning my expected results. Here's my code as it is now. I've tried many variations of the variable in the SQL statement after the LIKE and nothing has returned an array as expected. I've also verified that the $search variable does have the correct string in it.
index.php action switch (this works correctly):
case 'search_result':
    $search = filter_input(INPUT_POST, 'searchBar');
    $results = search_books($search);
    if($results == NULL){
        include('/view/search_null.php');
    }else {
        include('/view/search_results.php');
    }
    break;

My db search function:
function search_books($search_word){
global $db;
$query = ' SELECT * FROM books
           WHERE bookTitle LIKE :search_word  ';
$statement = $db->prepare($query);
$statement->bindValue(":search_word", $search_word);
$statement->execute();
$results_search = $statement->fetchAll();
$statement->closeCursor();
return ($results_search);
}

Every time $results is NULL and kicks me to my page that returns no results, even if it should return results. On that page I verify that $search has the correct word in it and that the array size of $results and $results_search is 0.
(Yes I know I should be cleansing the $search, this isn't going live it's just for an assignment)

What you are looking for is to surround the search term with wildcards by adding % to the search word, like so:
$search_word = '%' . $search_word . '%';


And then just prepare / bind / execute as you already are. This is your code after the change:
function search_books($search_word){
    global $db;
    $search_word = '%' . $search_word . '%'; // added
    $query = ' SELECT * FROM books
           WHERE bookTitle LIKE :search_word  ';
    $statement = $db->prepare($query);
    $statement->bindValue(":search_word", $search_word);
    $statement->execute();
    $results_search = $statement->fetchAll();
    $statement->closeCursor();
    return ($results_search);
}


The query would look something like this after the parameter get its place:
SELECT * FROM books WHERE bookTitle LIKE '%something here%'

That will look for anything that contains $search_word. Example:
For $search_word as Rings:
The Lord of the Rings: The Return of the King would be a match.
You can read more about that in here: Pattern Matching.

0 comments:

Post a Comment