Trying to D.R.Y. things up a bunch, but totally untested, so buyer beware:
<?php
include 'config.php';
if(isset($_GET['search'])) {
$wheres = [];
foreach(['title', 'location'] as $search) {
if($value = safe_value($conn, $seardh)) { // something was entered for that search
foreach(['title', 'company', 'category', 'description', 'time'] as $column) {
$wheres[] = "`$column` LIKE '%$value%'";
}
}
}
if(count($wheres)) { // at least one of the search fields was set
$sql = "SELECT * FROM `products` WHERE\n".implode(" OR\n", $wheres)."\nORDER BY id DESC";
// uncomment the following if you want to debug the query:
// die("<pre>$sql</pre>");
$query = mysqli_query($conn, $sql) or die(mysqli_error());
while($items = mysqli_fetch_assoc($query)) {
// do stuff with result
}
} else {
// whatever you want to do if neither search field was supplied
}
}
function safe_value(mysqli $conn, string $name) {
if(!isset($_GET[$name]) or trim($_GET[$name]) === '') {
return false;
}
// might want to add strtolower() or strtupper to this?
return mysqli_escape_string($conn, trim($_GET[$name]));
}
If you want to force the search term to lower-case, for example, change the last line of that function to:
return mysqli_escape_string($conn, strtolower(trim($_GET[$name])));
(I need one of those "buy me a coffee" links or something. )