:php mysql按邮政编码搜索过去在我们的网站上工作,但现在返回错误:邮政编码未被识别“;

:php mysql按邮政编码搜索过去在我们的网站上工作,但现在返回错误:邮政编码未被识别“;,php,mysql,Php,Mysql,我们的网站有一个商店搜索,它工作得很好,但不知何故,前一段时间它开始返回一个错误,上面写着“该邮政编码未被识别”。我不确定要复制并粘贴哪些信息给你看,因为我对php和mysql太陌生了。有人能帮我吗?我正处于时间紧迫的时期。 以下是php页面代码: <?php /** * The template used for displaying page content in dealersearch-page.php * * @package WordPress * @subpack

我们的网站有一个商店搜索,它工作得很好,但不知何故,前一段时间它开始返回一个错误,上面写着“该邮政编码未被识别”。我不确定要复制并粘贴哪些信息给你看,因为我对php和mysql太陌生了。有人能帮我吗?我正处于时间紧迫的时期。 以下是php页面代码:

  <?php
/**
 * The template used for displaying page content in dealersearch-page.php
 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 * @since Twenty Eleven 1.0
 */

/*==============================================================================
Application: Easy Postcode Finder
Author: Leon Chevalier
Version: V1.0
Date: 16th December 2007
URL: http://aciddrop.com/2007/12/17/quick-easy-and-free-nearest-store-postcodezip-finder/

alt: http://code.google.com/apis/maps/articles/phpsqlsearch_v3.html
------------------------------------------------------------------------------*/
/** 
* The curl class
*/  


/*
HOW TO UPDATE!!!
?update=all
?update=fixzeros
?update=new
*/

define('TOTAL_SEARCHED', 10);

class curl {

    /** 
    * COnstructor
    */  
    function curl() {



    }

    function init_curl($ch,$url,$postfields=null,$follow=null,$cookie=null,$referer=null) {

        // Set url
        curl_setopt($ch, CURLOPT_URL, $url);

        // Enable Post
        if($postfields) {
            curl_setopt ($ch, CURLOPT_POST, 1);
            curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
        }

        if($follow) {
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1 );      
        }

        if($referer) {
        curl_setopt($ch, CURLOPT_REFERER, $referer);
        }

        //Enable SSL
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);


        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');

        //Return results as string
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        return $ch;

    } // end function


    /*
    Grabs a page
    */

    function get_page($options) {

    //Set options
    foreach($options AS $key=>$value) {
    $$key = $value; 
    }   

        $ch = curl_init();      
        $ch = $this->init_curl($ch,$url,$postfields,$follow,$cookie);
        $page = curl_exec($ch);
        curl_close($ch);
        return $page;


    }


} // end class

/**
 * A simple wrapper for db functions
 *
 */
class db_custom {

    /**
     * Constructor
     *
     * A simple wrapper for database functions
     *
     */ 
    function db_custom()    {

    // database configuration
    $host = "localhost";
    $user = "codaonline";
    $pass = "***********";
    $db = "codaonline"; 

    // open database connection
    $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
    // select database
    mysql_select_db($db) or die ("Unable to select database!");


    }

    ###############################################
    ## Updates an array of fields and values
    ## and reurn the resulting ID
    ###############################################
    function quick_update($database,$fields,$values,$wherearray) {
    //Variables
    $num_array = count($values);
    //Format NULL
    $values = str_replace("'NULL'","NULL",$values);
    //Write query
    $query = "UPDATE `$database` SET ";
    foreach ($fields AS $key=>$value) {
    $count++;
    $query .= " $fields[$key] = '$values[$key]'";
    if ($count <> $num_array) { $query .= ","; }
    }
    //Create where
    foreach ($wherearray AS $key=>$value) {
    $counterv++;
        $query_chk .= "$key = '" . trim($value) . "'";

            if ($counterv != count($wherearray)) {
            $query_chk .= " AND ";
            }
    }

    $query .= " WHERE $query_chk";
    $query = str_replace("'`","",$query);
    $query = str_replace("`'","",$query);


    $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
    $rows = mysql_affected_rows();
    return $rows;
    }


    ######################################################
    # Execute row
    # runs query and gets row back
    ######################################################
    function executeRow($query__ER,$type=null) {
    $result__ER = mysql_query($query__ER) or die ("Error in query: $query__ER. " . mysql_error());
        if($result__ER != 1) {
            if($type!="array") {
            $row__ER = mysql_fetch_object($result__ER);
            } else {
            $row__ER = mysql_fetch_assoc($result__ER);
            }
        return $row__ER;        
        }
    }

    ######################################################
    # Connects to the database and returns the 
    # results in an array
    ######################################################

    function executeQuery($query,$func=null,$type="") {

        //Get the table name from the query
        preg_match("/SELECT(.*)FROM( )([A-z_]+)/i",$query,$matches);
        $table_name = $matches[3];

    $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
    $rows = mysql_num_rows($result);
    $columns = mysql_fetch_assoc($result);

        if ($rows > 0) { // Only proceed if we have a result

        mysql_data_seek($result,0);
            while ($row=mysql_fetch_array($result)) {

                foreach ($columns As $key=>$value) {


                            //Run any extra functions that have been sent over
                            if(is_array($func)) {           
                                foreach ($func AS $Fkey=>$Fvalue) {                     
                                $row[$key] = $this->$Fvalue($row[$key],$key,$table_name);               
                                } // end FE         
                            } // end IF

                                if($type == "object") {
                                //echo $key . "  "  . $row[$key] . "\n";
                                $tmp->$key = $row[$key];                
                                } else {
                                $tmp[$key] = $row[$key];
                                }

                }// end for each

                    $results[] = $tmp;
                    unset($tmp);
            } //end while 

        $final_result['result'] = $results;
        $final_result['rows'] = mysql_num_rows($result);        
        } else {
        $final_result['rows'] = 0;      
        }// end if

    return $final_result;

    } // end function


}

/**
 * A postcode finder class
 *
 */
class postcode_finder {

    /**
    * Constructor
    *
    */
    function postcode_finder($array) {

        if(is_array($array)) {
            foreach($array AS $key=>$value) {
            $this->$key = $value;
            }
        }   

        //DO stuff

    }

    /**
    * Setup database tables and insert lat longs
    *
    */  
    function setup()
    {
        //DONT EXECUTE THE 2 FUNCTION BELOW, SINCE THE DB IS ALREADY SET UP
        //$this->create_store_table();
        //$this->insert_example_stores();

        $this->update_lat_lngs();   
    }

    /**
    * Makes an example store table
    *
    */  
    function create_store_table()
    {
        //Create table
        $query = "CREATE TABLE IF NOT EXISTS `store` (
          `id` int(10) NOT NULL auto_increment,
          `name` varchar(75) NOT NULL default '',
          `address` text NOT NULL,
          `postcode` varchar(10) NOT NULL default '',
          `lat` double NOT NULL default '0',
          `lng` double NOT NULL default '0',
          `domain` varchar(10) NOT NULL default '',
          PRIMARY KEY  (`id`)
        ) ENGINE=MyISAM";
        $this->db->executeRow($query);  
    }

    /**
    * Insert some example stores
    *
    */  
    function insert_example_stores()
    {
        //for($i=0;$i<1000;$i++) {
            $query = "
            INSERT INTO `store` (`name` , `address` , `postcode`, `domain`) 
            VALUES (
            'Waterloo Station', 'Lambeth, London', '90277', 'com'
            ), (
            'Gatwick Airport ', 'South Terminal, Gatwick', 'RH6', 'co.uk'
            ), (
            'Edinburgh Waverley Railway Station ', 'Network Rail, Room 255, North Block, Edinburgh', 'EH1 1BB', 'co.uk'
            ), (
            'Beverly Hills', 'California', '90210', 'com'
            ), (
            'Penn Station ', '17 W 32nd St New York', '10001', 'com'
            ), (
            'La Sagrada Familia', 'Barcelona', '08013', 'es'
            ), (
            'FC Bayern Munchen', 'Sabener Str. 51, Munchen, Germany ', '81547', 'de'
            )       
            ";

            $this->db->executeRow($query);  
        //}
    }

    /**
    * Update lat lngs
    *
    */  
    function update_lat_lngs()
    {       
        //Get the list of stores
        //$query = "SELECT * FROM store WHERE `lat` = ''";
        if($_GET['update'] == "new")
        {
            $query = "SELECT * FROM store WHERE `lat` IS NULL";
        }
        else if($_GET['update'] == "fixzeros")
        {
            $query = "SELECT * FROM store WHERE `lat` = '0.000000'";
        }
        else
        {
            $query = "SELECT * FROM store";
        }
        $stores = $this->db->executeQuery($query);
        $stores = $stores['result'];

        //Run through stores and get lat / lng
        foreach($stores AS $store) {

            $latlng = $this->get_lat_long($store['postcode'],$store['domain']);

            //Update store with its lat lng
            $this->db->quick_update("store",
                                    array('lat','lng'),
                                    array($latlng['lat'],$latlng['lng']),
                                    array('id'=>$store['id'])
                                    );
        }
    }

    /**
    * Returns a lat / long of a given postcode
    *
    */  
    function get_lat_long($postcode,$domain=null) {

        if(!$domain) {
            $domain = "com";
        }

        $url = "http://maps.google." . $domain . "/maps/geo?q=" . urlencode($postcode) . "&output=json&key=ABQIAAAAd68ReBKRz0DIUqnh0urYdhR0Q3-qVDTU2G-tuQrQTRhYanhS-xTuF2SEKlLS-kmZKBwQN9ukjwTT_A";

        $json = $this->curl->get_page(array("url"=>$url));

        $store_data = json_decode(str_replace("&quot;","\"",htmlentities($json))); //Take care of accents

        $lng = $store_data->Placemark[0]->Point->coordinates[0];            
        $lat = $store_data->Placemark[0]->Point->coordinates[1];

            //Return
            if($lng && $lat) {

                return array('lat'=>$lat,
                             'lng'=>$lng
                             );

            } else {

                return false;

            }

    }


    /**
    * Get a list of our stores, sorted by distance to this postcode
    *
    */  
    function get_stores_list($postcode) {

        //If it's a UK postcode then format correctly
        $postcode = $this->checkPostcode($postcode);

        $latlng = $this->get_lat_long($postcode);

        if(!$latlng) { //Unrecognised postcode
        return false;
        }

        $latitude = $latlng['lat'];
        $longitude = $latlng['lng'];        
//      print_r($latlng);

        $query = "SELECT *,
                    (((acos(sin((".$latitude."*pi()/180)) * sin((`lat`*pi()/180))
                    +cos((".$latitude."*pi()/180)) * cos((`lat`*pi()/180)) 
                    * cos(((".$longitude."- `lng`)*pi()/180))))*180/pi())*60*1.1515) 
                    as distance 
                        FROM `store`
                        ORDER BY distance ASC
                        LIMIT 0,".TOTAL_SEARCHED;
        $stores = $this->db->executeQuery($query);
        $stores = $stores['result'];            

        return $stores;

    }


    /**
    * Checks whether supplied postcode is a valid UK postcode
    */
    function checkPostcode($toCheck) {

      $orig = $toCheck;

      // Permitted letters depend upon their position in the postcode.
      $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
      $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
      $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
      $alpha4 = "[abehmnprvwxy]";                                     // Character 4
      $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5

      // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
      $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$';

      // Expression for postcodes: ANA NAA
      $pcexp[1] =  '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$';

      // Expression for postcodes: AANA NAA
      $pcexp[2] =  '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$';

      // Exception for the special postcode GIR 0AA
      $pcexp[3] =  '^(gir)(0aa)$';

      // Standard BFPO numbers
      $pcexp[4] = '^(bfpo)([0-9]{1,4})$';

      // c/o BFPO numbers
      $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$';

      // Load up the string to check, converting into lowercase and removing spaces
      $postcode = strtolower($toCheck);
      $postcode = str_replace (' ', '', $postcode);

      // Assume we are not going to find a valid postcode
      $valid = false;

      // Check the string against the six types of postcodes
      foreach ($pcexp as $regexp) {

        if (ereg($regexp,$postcode, $matches)) {

          // Load new postcode back into the form element  
          $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]);

          // Take account of the special BFPO c/o format
          $toCheck = ereg_replace ('C\/O', 'c/o ', $toCheck);

          // Remember that we have found that the code is valid and break from loop
          $valid = true;
          break;
        }
      }

      // Return with the reformatted valid postcode in uppercase if the postcode was 
      // valid
      if ($valid){
      return $toCheck;
      } else {
      $this->non_standard_postcode = true;
      return $orig;
      };

    }   


}

//If we have a post
if($_POST['postcode'])
{ 
    //Start database class
    $db = new db_custom();
    $curl = new curl();
    $finder = new postcode_finder(array('db'=>$db, 'curl'=>$curl));                       
    $stores = $finder->get_stores_list($_POST['postcode']);                       
}

if($_GET['update'])
{
    $db = new db_custom();
    $curl = new curl();
    $finder = new postcode_finder(array('db'=>$db, 'curl'=>$curl));                       
    $finder->setup();
}

?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <h1 class="entry-title"><?php the_title(); ?></h1>
    </header><!-- .entry-header -->
    <hr>
    <div class="entry-content">
        <?php the_content(); ?>







        <!-- BEGIN SEARCH FORMATTING -->                                                                  
        <form action="#results" method="post" class="bigsearchform">
            <div class="bigsearch">
                Enter your ZIP or City and press Enter.<br/>
                For Example: "90505" or "Montclair, CA"
                <div>
                    <input class="searchbox" type="text" name="postcode" value="<?php echo $_POST['postcode']; ?>" placeholder="Enter your ZIP or City">
                    <input class="search-img" type="image" src="<?php echo get_template_directory_uri(); ?>/images/bigsearch.png" value="Submit" alt="Submit">
                </div>

            </div>
        </form>

        <div id="results"></div>        
        <?php if($_GET['update']) { ?>  
            <h2 style="background-color:padding:2px">Database Updated</h2>                              
        <?php } ?>

        <?php if ($_POST['postcode']) { ?>
            <?php if($stores) { ?>
                <h2>The following <?php //echo TOTAL_SEARCHED; ?> Installing Dealers were found near to you</h2>

                <?php foreach($stores as $store) { ?>
                <div class="dealer">
                    <div class="company"><?php echo $store['name']; ?> <span>is <span style="background-color:#ffffcc"><?php echo number_format($store['distance'],2); ?></span> miles from you</span></div>

                    <div class="contact">
                        <?php echo $store['contact']; ?>
                        <?php if($store['email'] != '') { ?>
                            (<a href="mailto:<?php echo $store['email']; ?>" target="_blank"><?php echo $store['email']; ?></a>)
                        <?php } ?>
                    </div>

                    <div class="map"><img src="http://maps.googleapis.com/maps/api/staticmap?markers=<?php echo $store['address']; ?> <?php echo $store['city']; ?> <?php echo $store['state']; ?> <?php echo $store['postcode']; ?>&size=320x150&zoom=14&sensor=false" width="320" height="150" /></div>

                    <div class="on-right">
                        <div class="address"><?php echo $store['address'] . ' ' . $store['address2']; ?><br/>
                        <?php echo $store['city']; ?>, <?php echo $store['state']; ?> <?php echo $store['postcode']; ?></div>

                        <div class="phonefax">Phone: <?php echo $store['phone']; ?><br />
                        Fax: <?php if($store['fax'] != '') echo $store['fax']; else echo "N/A"; ?></div>

                        <?php if($store['url'] != '') { ?>
                            <div class="url"><img src="<?php echo get_template_directory_uri(); ?>/images/link.png" width="16" height="16" alt="Website Link" /> <a href="<?php echo $store['url']; ?>" target="_blank"><?php echo $store['url']; ?></a></div>
                        <?php } ?>

                        <div class="otherinfo">License #: <?php echo $store['license']; ?> &mdash; <?php echo $store['keybusiness']; ?></div>
                    </div>

                </div>
                <?php } ?>
            <?php } else { ?>
                <h2>That postcode was not recognized</h2>               
            <?php } ?>  
        <?php } ?>







    </div><!-- .entry-content -->
    <footer class="entry-meta">
        <?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?>
    </footer><!-- .entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->

允许路由通过此错误

        <?php } else { ?>
            <h2>That postcode was not recognized</h2>               
        <?php } ?>  
我已经开始你的搜索了。这取决于你去看看为什么你的病情会恶化

我还建议看一下
isset()
,而不是
if($var)



总而言之,我的猜测是,
$stores
甚至没有设置或返回false,因此落入
if
语句中的
else
子句中。

看看你的
get\u lat\u long
函数:

$url = "http://maps.google." . $domain . "/maps/geo?q=" . urlencode($postcode) . "&output=json&key=ABQIAAAAd68ReBKRz0DIUqnh0urYdhR0Q3-qVDTU2G-tuQrQTRhYanhS-xTuF2SEKlLS-kmZKBwQN9ukjwTT_A";
现在。我明白了

谷歌 我们很抱歉。。。 。。。但您的计算机或网络可能正在发送自动查询。为了保护我们的用户,我们现在无法处理您的请求

显然,该URL不应该被其他人用作API。谷歌注意到并阻止了你。您必须找到一个API,您实际上可以使用它来获取纬度和经度。

如果
$stores
为false,则会显示“此邮政编码未被识别”一行

这是定义它的行:

$stores = $finder->get_stores_list($_POST['postcode']); 
我将在get_stores_list函数中的查询旁边放置一个
echo
命令,查看查询是否正常,然后在数据库中运行它。你必须把事情的范围缩小一点,以获得社区的更多帮助。

问题

地理编码API v2已于2013年9月9日被拒绝。这个 现在应该使用地理编码API v3

解决方案


我希望这不是您的实际数据库密码。如果是这样的话,请立即在服务器上进行更改。老实说,你最好的选择可能是与整合你的网站的人交谈,或者雇佣一名现场开发人员。因为解决这一问题需要的不仅仅是查看单个文件。需要进行测试(是所有地址阻塞还是部分地址阻塞?),检查数据库是否正在运行且未受损等功能。在文件>选择要扫描的文件目录>扫描字符串“未识别邮政编码”中查找>阅读上面的代码行,找出导致定义此
用户错误的条件,并修复过多的代码。这太模糊,无法在上成功调试。我最好的建议是找一个能花时间在上面的程序员。@JohnMcMahon:比这更糟糕。他们的MySQL服务向互联网公开。
$url = "http://maps.google." . $domain . "/maps/geo?q=" . urlencode($postcode) . "&output=json&key=ABQIAAAAd68ReBKRz0DIUqnh0urYdhR0Q3-qVDTU2G-tuQrQTRhYanhS-xTuF2SEKlLS-kmZKBwQN9ukjwTT_A";
$stores = $finder->get_stores_list($_POST['postcode']);