I have a piece of code that works, however it's pretty messy. The objective is to retrieve all the relevant rows from a user search. For example: If the user searches 'Jo', it will retrieve John and Josh:
The code that works:
if($_SERVER["REQUEST_METHOD"] == "POST") {
$search = trim(filter_input(INPUT_POST,"user_search",FILTER_SANITIZE_SPECIAL_CHARS));
$search = preg_replace("#[^0-9a-z]#i", "", $search);
if(!isset($error_message)) {
$query = $db->query("SELECT * FROM User WHERE U_Forename LIKE '%$search%'
OR U_Surname LIKE '%$search%' OR U_Team LIKE '%$search'
OR U_City LIKE '%$search%'");
}
}
<?php
if ($query->num_rows == 0) {
$output = "No results found!";
} else {
echo "<h2>Search results for: " . $search . "</h2>";
while($row = $query->fetch_assoc()) {
$id = $row['U_ID'];
$firstname = $row['U_Forename'];
$lastname = $row['U_Surname'];
$team = $row['U_Team'];
$city = $row['U_City'];
echo "<div class='searchresults'>";
echo "<p> Name: " . ucfirst($firstname) . " " . ucfirst($lastname) . "</p>";
echo "<p> Favourite Team: " . ucfirst($team) . "</p>";
echo "<p> Location: " . ucfirst($city) . "</p>";
echo "<a class='lift' href='profile.php?=[$id]'>View Profile</a>";
echo "<a class='lift' href='#'>Follow Driver</a>";
echo "</div>";
}
}
?>
What I have tried:
function getSearchResults($search) {
global $db;
$searchArray = array();
$query = $db->query("SELECT * FROM User WHERE U_Forename LIKE '%$search%'
OR U_Surname LIKE '%$search%' OR U_Team LIKE '%$search'
OR U_City LIKE '%$search%'");
if ($query->num_rows == 0) {
echo "No results found!";
} else {
while($row = $query->fetch_assoc()) {
$searchArray['U_ID'] = $row['U_ID'];
$searchArray['U_Forename'] = $row['U_Forename'];
$searchArray['U_Surname'] = $row['U_Surname'];
$searchArray['U_Team'] = $row['U_Team'];
$searchArray['U_City'] = $row['U_City'];
}
}
return $searchArray;
}
However this will not work as only the first result from the fetch_assoc() is stored in the $searchArray and nothing else! Does anyone have any suggestions? I am unsure on where to begin coding next.
James.