Question

Searching substring in all columns of the table.Result to be displayed in following order:
1.first results starting with substring.
2.Then results in which substring in middle and not at last.
3.Then results in which substring is at last.
The problem arises when searching for substring in middle and not at last because like %substring% will also contain %substring which is actually at last.So the order is not preserved.

foreach($results as $r){
$append1 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." like'".$substring."%'union ";
$query1 = $query1.$append1;
}  
foreach($results as $r){
$append2 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." like'%".$substring."%'union";
$query2 = $query2.$append2;
}
foreach($results as $r){
$append3 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." like'%".$substring."'union";
$query3 = $query3.$append3;
}
$query4=$query1.$query2.$query3;
$query4 = substr($query4, 0, -5);
Was it helpful?

Solution

The LIKE operator uses two wildcard characters. You already know about %, but there's also _ (which basically means "exactly one of any character").

So you can do the second query like

$append2 ="SELECT * FROM $tablename WHERE {$r['COLUMN_NAME']} LIKE '_%{$substring}%_' union";

and it should only match where there's at least one character before $substring and one after.

OTHER TIPS

You'll need to add in an extra bit to the WHERE clause to exclude where the string is at the end.

$append2 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." like '%".$substring."%' AND ".$r['COLUMN_NAME']." NOT like '%".$substring."' union";

As an aside, mysql_* functions are deprecated, and you should really look into mysqli or PDO.

You could use regular expressions instead. For example:

 $append1 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." REGEXP '".$substring."$' union ";  // match ending

 $append1 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." REGEXP '[[:print:]]".$substring."[[:print:]]' union ";  // match middle

 $append1 ="select * from ".$tablename." WHERE ".$r['COLUMN_NAME']." REGEXP '^".$substring."' union ";  // match beginning
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top