SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,316
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Need proper query to search for zip code with regex

    I just heard that the proper way to search via ZIP code in the U.S. is by the first three digits. I'm trying to use regular expressions to do this, but can't get the syntax right. Here's what I have. It comes up blank with no error messages:

    PHP Code:
    if(isset($_POST['postalcode'])) 
    {
        
    $postalcode $_POST['postalcode'];
        
    $postalcode strip_tags($postalcode);
        
    $postalcode trim($postalcode);
        
    $postalcode htmlspecialchars($postalcode);

        
    // Grab first three digits of the zip code.
        
    $first3 substr('$postalcode'03);

    $searchsql mysql_query 
        
    ("SELECT ID, Shop, Track, Country, Name, Street1, Street2, City, State, Zipcode, Phone, Fax, Email, WebSite, TrackInfo
        FROM shopdirectory
        WHERE Zipcode LIKE '%
    $first3%' ORDER BY Zipcode ASC
        "
    );
    if (!
    $searchsql) {
        die(
    'Invalid query: ' mysql_error()); } 
    Is my regular expression wrong or the query?

    Thanks!

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,018
    Mentioned
    53 Post(s)
    Tagged
    2 Thread(s)
    WHERE Zipcode LIKE '$first3%'

    notice no leading wildcard character

    and by the way, LIKE and REGEXP are completely different
    r937.com | rudy.ca | Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,316
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I could put '92708' in the search box for the old code and it would return one result. This change in the code did not return anything.

    I guess substr() is not a regex but a function. Faux pas!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •