Hey all,
Hope someone out there can help a new up and coming php guy
i have a mysql database that contains a numerous amount of zip codes. Right now i have a zip code searching going and it is working just fine. But how can i do that same zip code search by searching with only the first three digits of the zip code entered by the user?
<?php
$userzip = $_POST['zip']; // Validate this for security reasons
$sql = "SELECT LEFT('zip', 3) AS zipcode FROM my_table WHERE zipcode = $userzip";
?>
Everah wrote:You could also do an exact match using the LEFT() mysql function. Not sure what the results would be as far as performance, but it could be done.
<?php
$userzip = $_POST['zip']; // Validate this for security reasons
$sql = "SELECT LEFT('zip', 3) AS zipcode FROM my_table WHERE zipcode = $userzip";
?>
Another thing to keep in mind is some zip code databases will have zip codes with leading zeros not show the leading zero. so 00564 would be 564
I was thinking on the way home that the query I put submitted was not correct. It will truncate the zip field and return only the first three chars of the thing. That is probably not what the poster wants. I think this might be in order...
<?php
$userzip = $_POST['zip']; // Validate this for security reasons
$sql = "SELECT zip, LEFT('zip', 3) AS zipcode FROM my_table WHERE zipcode = $userzip";
?>
hawleyjr wrote:Another thing to keep in mind is some zip code databases will have zip codes with leading zeros not show the leading zero. so 00564 would be 564.
I store my zip codes as string values to keep this from happening. My very first zip code app ran into the very problem that you mentioned. It didn't take long for me to change the field type.