Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SELECT LIKE '&' and NULL values 1

Status
Not open for further replies.

cmayo

MIS
Apr 23, 2001
159
US
My client's PHP ticketing system has a search form at the top of most of its tabular pages, and the tabular data is generated by MySQL using search form fields and wildcarded LIKE statments, i.e.

[pre]SELECT *
FROM inventory
WHERE part_number LIKE '{$_POST['part_number']}%'
AND description LIKE '{$_POST['description']}%'[/pre]

This works well enough in most cases. There are no search criteria on initial page load so the queries all tend to be wildcarded and all data is returned:

[pre]
SELECT *
FROM inventory
WHERE part_number LIKE '%'
AND description LIKE '%'[/pre]

and most searches are done on only one or two fields, so a more typical query will look like:

[pre]
SELECT *
FROM inventory
WHERE part_number LIKE '654%'
AND description LIKE '%'[/pre]

This method works fine unless some of the records contain NULL's in the search fields, in which case those records are omitted since LIKE '%' doesn't match a NULL value.

So I'm looking at a better way to write that code.

All I can think to do is to kludge the WHERE conditions with PHP so the LIKE statements aren't included unless the user has entered search text for that field, i.e. if the user doesn't give us a description to search for, the query won't contain a "description LIKE '%'" condition, hence NULL's in the description field won't be an issue.

Is there a better way?
 
how about this>

Code:
$query = "
SELECT * 
FROM inventory 
WHERE ifnull(part_number,'zzz') LIKE '" . mysql_real_escape_string($_POST['part_number']) . "%' 
AND ifnull(description,'zzz') LIKE '". mysql_realt_escape_string($_POST['description']) . "'";

 
JPADIE, you absolutely rock. Thank you very much!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top