2

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:

enter image description here

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

enter image description here

My database location looks like

enter image description here

Where am i going wrong from my code? Any help will be appreciated

Omari Victor Omosa
  • 2,814
  • 2
  • 24
  • 46

1 Answers1

2

If you want to display the information you have to concatenate a string (which I do with the implode())instead of creating a JSON object:

//get search term
$searchTerm = htmlspecialchars($_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 = $row['location']; 
    array_push($data, $name);   
}   

$string = '"' . implode('","', $data) . '"';
$newString = str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>", $string); 
echo $newString;

Once you have created a string then you can do the replace to add the markup to the string.


Your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. I have done the bare minimum in this code by using htmlspecialchars().

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119