开发者

SQL Query wildcard

Is there a way to do a SQL query with a wildcard or search for with contain.

Currently users can search my database for an address. Using the LIKE command they can search for 123 Fake St. But is there a way to perform a search using 123, and then have it display all the addresses that have 123 in them. Example: Search for 123 -> Results: 123 Fake St, 123 Spooner Ave, 123 Example Terrace.

Is there a way to perform a search like that? My code for the current search function is below: On the previous page the user enters an address they want to search for, that value is stored in $street.

$sql = ("SELECT  sitestreet FROM  `PropertyInfo` WHERE  `sitestreet` LIKE  '$street' AND `user` LIKE '$user'");
$result = mysq开发者_如何学Cl_query($sql);

Thanks!


The sql wildcard is '%' use that within a like

"SELECT sitestreet FROM PropertyInfo WHERE sitestreet LIKE '%$street%' AND user LIKE '$user'"


Try

$sql = ("
  SELECT sitestreet 
  FROM PropertyInfo 
  WHERE sitestreet LIKE '%$street%' 
    AND user LIKE '$user'"); 
$result = mysql_query($sql)


$sql = ("SELECT sitestreet FROM PropertyInfo WHERE sitestreet LIKE '$street%' AND user = '$user'"); 
$result = mysql_query($sql);

For user I would not use the LIKE operator, but =


Like so:

LIKE '%$street%';

The wildcards are _ (single char) and % (multiple chars).


Using your query above, this is all you need...

SELECT sitestreet FROM PropertyInfo WHERE sitestreet LIKE '%street' AND user LIKE '%user'

The % symbol is a wildcard used for multiple characters. It will return records with ANY character/s before street, and the same for user.


you have to use

SELECT sitestreet FROM PropertyInfo WHERE sitestreet LIKE '%$street' 

or

SELECT sitestreet FROM PropertyInfo WHERE sitestreet LIKE '%$street%' 

http://www.techonthenet.com/sql/like.php


Building SQL query text on the fly when it contains user input is a great way to make yourself vulnerable to SQL injection attacks.

For something like this what you should be doing is creating a parameterized stored proc that will do the type of search you want, in the example above you might name it something like

GetSiteStreetByUserAndPartialAddress

Then have your code call that sproc with the username and user supplied address search value as parameters

That ensures your site will not become the butt of XKCD comics about someone named: bobby'); DROP TABLE Users;-- or in your case have a user search for something along the lines of

123 Pwned Way'); DROP TABLE PropertyInfo; --
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜