JayIsTooCommon
JayIsTooCommon

Reputation: 1714

PHP to search SQL for exact and LIKE

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?

Upvotes: 0

Views: 421

Answers (4)

Sulaiman Adeeyo
Sulaiman Adeeyo

Reputation: 495

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.

Upvotes: 0

jtb
jtb

Reputation: 149

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'

Upvotes: 0

Logan Wayne
Logan Wayne

Reputation: 5991

Does

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

out of the option?

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

Remove the %. Try with -

SELECT * FROM cars WHERE Name LIKE '$searchq' OR Reg LIKE '$searchq'

Upvotes: 1

Related Questions