Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

php - MYSQL Queries using LIKE

I'm trying to use PHP to query MYSQL for some exact matches and some partial matches. The following code give me perfect exact matches for all fields:

$results= mysql_query ("SELECT * 
                          FROM companyinfo 
                         WHERE id='$Companyid' 
                            OR companyname='$Companyname' 
                            OR contactname='$Contactname' 
                            OR address1='$Address1' 
                            OR city ='$City' 
                            OR primaryphone='$Primaryphone' 
                            OR email='$Email'")

I would like to be able to do a partial search on Company Name. Using the following code allows me to achieve this except it messes up all other search fields.

$results= mysql_query ("SELECT * 
                          FROM companyinfo 
                         WHERE id='$Companyid' 
                            OR companyname LIKE '%{$Companyname}%'
                            OR contactname='$Contactname' 
                            OR address1='$Address1' 
                            OR city ='$City' 
                            OR primaryphone='$Primaryphone' 
                            OR email='$Email'")

Anyone have any hints?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm reading into your question a bit here, but I'm pretty sure $Companyname is empty, leaving you with the query:

SELECT * 
FROM companyinfo 
WHERE id='20' 
OR companyname LIKE '%%'
OR ...

That WHERE companyname LIKE '%%' will match anything non-null; making all the other OR conditions moot. You'll need to set up a special case where $Companyname is empty, or simply not include unused search criteria in the predicate.


This is all, of course, assuming that OR is really what you mean to do here. In most searches I've done, the assumed UX has been to match all criteria I specify, not any. The only time any would apply is with a single search input, which your case clearly is not.

I should also include the obligatory "Your query is subject to SQL injection. Stop putting what is clearly user-input into dynamic queries, and use parameters instead." comment here as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...