Reputation: 5
I am new to php programming. I have set up a mysql database with
id,
city,
county,
state,
zip fields
My problem is the search form I have written works well on city and county query's, but will only accept 4 of the five numbers on a query for zip. I have researched and found nothing that helps. I thought it may be an issues with preg_replace()
, but have had no luck there.
I have tried different mysql query syntax with no luck.
$allowed = "/([0-9]{5})([0-9]{4})/";
$searchquery = preg_replace($allowed, '', $_POST['searchquery']);
if($_POST['filter1'] == "Zip Code"){
$sqlCommand = "SELECT city, county, zip, state FROM cities_extended WHERE zip LIKE '%$searchquery%' ORDER BY county, city, zip ";
Upvotes: 0
Views: 546
Reputation: 3719
Take a look at
$string="tampa, florida, 33616-1701";
preg_match("/([0-9]{5})-([0-9]{4})/",$string,$matches);
var_dump( $matches);
or
$allowed = "/([0-9]{5})-([0-9]{4})/";
preg_replace($allowed, $_POST['searchquery'],$matches);
$searchquery=$matches[0];
if($_POST['filter1'] == "Zip Code"){
$sqlCommand = "SELECT city, county, zip, state FROM cities_extended WHERE zip LIKE '%$searchquery%' ORDER BY county, city, zip ";
Upvotes: 0
Reputation: 536
Looks like you're missing a dash in your regex if you're trying to process zip+4. Your code also doesn't quite make sense. You aren't trying to replace anything the user puts in, you're trying to find out if what they put in is a valid zip code? Instead of preg_replace, which replaces a string, try preg_match, which lets you know if they put in a valid zip code.
It should read something like this:
$allowed = "([0-9]{5})-([0-9]{4})";
if($_POST['filter1'] == "Zip Code"){
if(preg_match($allowed, $_POST['searchquery']))
{
$sqlCommand = "SELECT city, county, zip, state FROM cities_extended WHERE zip LIKE '%$searchquery%' ORDER BY county, city, zip ";
}
}
Upvotes: 2