简体   繁体   中英

Search MySQL database where fields contain symbols

I have a location database on my MySQL server containing UK postcodes, postal towns, counties and coordinates. If one were to search for "connahs" (real result is "Connah's Quay"), no results would be returned because they did not include the apostrophe. The same applies to hyphens and other symbols.

In this example, the postal town "Connah's Quay" is the correct format, so I can't just remove the symbol from the database.

My query so far is:

SELECT * FROM uk_postcodes WHERE postal_town LIKE "connahs%" ORDER BY postal_town LIMIT 25

Is there any way I can search for fields both containing symbols (connah's) and not (connahs) so that regardless of whether the user uses the apostrophe it returns results?

Use mysql replace function. Query will be like this:

SELECT * FROM uk_postcodes WHERE  REPLACE( postal_town, "'", "" )   
LIKE "connahs%" ORDER BY postal_town LIMIT 25

Hope it will help you.

I assume you are using php in your code.

// get the value of searched word from searchbox or something...
$keyword = $_POST['uk_postcodes'];
// avoid sql injection to, also read for special characters
$keyword = mysql_real_escape_string($keyword);
$keyword = stripslashes($keyword);

$query = "SELECT * FROM uk_postcodes WHERE postal_town LIKE %$keyword ORDER BY postal_town LIMIT 25";

In the code above, you can type anything!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM