I am trying to highlight my search result in PHP search but it highlights undesiraby
I use the code below
//connection to db
define('DB_HOST', 'localhost');
define('DB_NAME', 'dbname');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
//get search term
$searchTerm = $_GET['term'];
$result = mysqli_query($con, "SELECT `location` FROM `locations` WHERE TRIM(location) LIKE '%".($_GET['term'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result))
{
$name = str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>", $row['location']);
array_push($data, $name);
}
//return json data
echo json_encode($data);
Lets say I search for the term makutano I end up getting a result like the one displayed below:
I would expect it only to highlight makutano
, but it does not work as intended.
If i remove the str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>"
code my result would be as diplayed in the image below
My database location looks like
Where am i going wrong from my code? Any help will be appreciated