I have a code in PHP and I want to use == operator to search only exact terms and also have the search not case sensitive. The first thing doesn't work when I change LIKE to ==.
<?php $con = mysql_connect('********','********','********'); mysql_select_db("********",$con); function search_results($keywords){ $returned_results = array(); $where =""; $keywords = preg_split('/[\s]+/',$keywords); $total_keywords = count($keywords); foreach($keywords as $key=>$keyword){ $where .= "`keywords` LIKE '%$keyword%'"; if($key != ($total_keywords -1)){ $where .=" AND "; } } $results = "SELECT name, image_url, game_url, alt FROM search_games WHERE $where"; $results_num = ($results =mysql_query($results))? mysql_num_rows($results):0; if($results_num === 0){ return false; } else{ while ($results_row = mysql_fetch_assoc($results)) { $returned_results[] = array( 'name' => $results_row['name'], 'image_url' => $results_row['image_url'], 'game_url' => $results_row['game_url'], 'alt' => $results_row['alt'] ); } return $returned_results; } } ?> 12 Answers
Use MySql LOWER function to perform incasesensitive search:
... foreach ($keywords as $key => $keyword) { $keyword = strtolower($keyword); $where .= " LOWER(`keywords`) LIKE '%$keyword%'"; if ($key != ($total_keywords -1)) { $where .= " AND "; } } You could replace the foreach with the code below:
foreach($keywords as $key=>$keyword){ $keyword = strtoupper($keyword); $where .= "upper(`keywords`) = '$keyword'"; if($key != ($total_keywords -1)){ $where .=" AND "; } } The code above, makes the $keyword string to upper case and then in the sql query it compares it with the upper(keywords), so they both are upper case when compared.
Sources:
10