I am trying to make a search script that searches cars in a database and matches ALL keywords input by user. If I leave keywords text box empty and search I get results but if I input any keywords I get no results.
$search_keywords = $_POST['search_keywords'];
$terms = $search_keywords;
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = "'title' LIKE '%{$item}%'";
$types[] = "'exterior_colour' LIKE '%{$item}%'";
}
$sql = "SELECT * FROM list_car WHERE ";
$sql .= implode(" && ", $types) . " ORDER BY 'title'";
$result = mysqli_query($link, getPagingQuery($sql, $rowsPerPage));
UPDATE:
Works now i have changed it but if i search Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg
all the Toyota hilux
will appear but dfkjodsgfudsugfdsgfgfgfdgfdg
is garbage which is not listed in the database i want it to match ALL keywords not just one or more.
$search_keywords = $_POST['search_keywords'];
$terms = $search_keywords;
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = "`title` LIKE '%{$item}%'";
$types[] = "`exterior_colour` LIKE '%{$item}%'";
}
$sql = "SELECT * FROM list_CAR WHERE ";
$sql .= implode(" || ", $types) . "";
$result = mysqli_query($link, getPagingQuery($sql, $rowsPerPage)) or die(mysqli_error($link));
Here's how I'd do it.
Note I'm using untested
mysqli
prepared statements, I haven't built the parameterized queries procedurally inmysqli
, I base this approach off user comments on the manual's page.This should give a query such as
Which will require each keyword is present in the title or the color list.
If you were to keep it unprepared, which is unrecommended and poor practice, it would be..
Output:
You should use
OR
(||
) instead ofAND
(&&
) . As it is, your search term must match against all fields: