0

I'm currently using the below query;

SELECT * FROM '' WHERE Name LIKE 'argument'
OR Reg LIKE 'argument'

However, this will only show results that are LIKE Name or Reg not exact.

How do I change this query to search for results that are exact and like?

JayIsTooCommon
  • 1,714
  • 2
  • 20
  • 30
  • Remove the '%' symbol – littleibex Apr 13 '15 at 08:20
  • If you only want to search for exact matches you can just remove `LIKE` and both `%` and replace it for `=` so it becomes `Name = '$searchq'`, when using the comparsion operator your query will execute faster. Read this for more info http://stackoverflow.com/questions/543580/equals-vs-like – Daan Apr 13 '15 at 08:22

4 Answers4

1

Remove the %. Try with -

SELECT * FROM cars WHERE Name LIKE '$searchq' OR Reg LIKE '$searchq'
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

or just use an equals operator for checking the Reg...

SELECT * FROM cars WHERE (Name LIKE ('%'. $searchq .'%') OR Reg = '$searchq')

Note: It may also be worth ensuring all letters in the Reg and search string are both upper case before doing the search. e.g.

 <%php $searchq = strtoupper($searchq); %>

 SELECT * FROM cars WHERE (Name LIKE ('%'. $searchq .'%') OR upper(Reg) = '$searchq'
jtb
  • 139
  • 7
  • Sorry, i had a typo in the query above - the % signs need to be in the LIKE part! – jtb Apr 13 '15 at 08:51
  • I've amended the second code section above. The % signs should be around the search string only for the LIKE comparison. – jtb Apr 13 '15 at 09:39
  • For the exact match, you should do and =, but you need to make sure that any letters in the data and the search string are converted to upper case. Just for the purposes of the comparison, so no need to change the data permanently! – jtb Apr 13 '15 at 09:41
0

Does

"SELECT * FROM cars WHERE Name = '$searchq' OR Reg = '$searchq'"

out of the option?

Logan Wayne
  • 6,001
  • 16
  • 31
  • 49
0

Change your SQL to this

$query = mysql_query("SELECT * FROM cars WHERE Name LIKE '%".$searchq."%' OR Reg LIKE '%".$searchq."%' OR Name = '".$searchq."' OR Reg ='".$searchq."'") or die(mysql_error());

I hope you are sanitizing your the search string. Not sanitizing it may leads to SQL Injection.

Sulaiman Adeeyo
  • 485
  • 6
  • 19