3

我从 codeigniter 和它生成这个 sql 查询中得到一个数据库语法错误。

SELECT `code`, `latitude`, `longitude` FROM (`postcodes`) WHERE `latitude` `BETWEEN 55`.`8616 AND 56`.`1508` AND `longitude` `BETWEEN '-3`.`9507' AND '-3`.`6131'` AND `code` LIKE 'FK%'

我想我可以看到问题是在它们不应该在经度和 lqatitudes 的地方添加''。

生成此查询的代码是:

 function get_zips_in_range($zip, $range, $sort=1, $include_base=true)
{
    //get base postcode details
    $details = $this->get_zip_point($zip);

    if( ! $details)
    {
        return false;
    }

    //get the first 2 letters of the postcode
    $str = substr($zip, 0, 2);

    //find max - min lat / long for radius and zero point and query
    //only zips in that range.
    $lat_range = $range/69.172;
    $lon_range = abs($range/(cos($details->latitude) * 69.172));
    $min_lat = number_format($details->latitude - $lat_range, "4", ".", "");
    $max_lat = number_format($details->latitude + $lat_range, "4", ".", "");
    $min_lon = number_format($details->longitude - $lon_range, "4", ".", "");
    $max_lon = number_format($details->longitude + $lon_range, "4", ".", "");

    //build the sql query
    $this->CI->db->select("code, latitude, longitude");

    if( !$include_base)
    {
        $this->CI->db->where("code <>", $zip);
    }

    $this->CI->db->where("latitude BETWEEN '$min_lat' AND '$max_lat'");
    $this->CI->db->where("longitude BETWEEN '$min_lon' AND '$max_lon'");
    $this->CI->db->like('code', $str, 'after');    
    $result = $this->CI->db->get("postcodes");

    if($result->num_rows() < 1)
    {
        $this->set_last_error("SQL error in get_zips_in_range");
        return false;
    }
4

4 回答 4

3

CI 2.1.1 中有一个错误https://github.com/EllisLab/CodeIgniter/issues/1469

恢复到 2.1.0 是最好的解决方案,直到 2.1.2 出来

于 2012-06-14T13:49:31.213 回答
1

CodeIgniter 会自动添加反引号以进行更安全的查询。如果要禁用此功能,可以添加参数 FALSE,如下所示:

$this->CI->db->where("latitude BETWEEN '$min_lat' AND '$max_lat'", FALSE);
于 2012-06-15T11:14:33.437 回答
1

好吧,看看下面的东西,

$this->CI->db->where("latitude BETWEEN $min_lat AND $max_lat");
$this->CI->db->where("longitude BETWEEN $min_lon AND $max_lon");

除了语法,它将被呈现为where latitude BETWEEN $min_lat AND $max_lat AND longitude BETWEEN $min_lon AND $max_lon

现在你会问是什么问题..

问题在于我们制作它的方式

可以按如下方式完成

$this->CI->db->where("(latitude BETWEEN $min_lat AND $max_lat)");
$this->CI->db->where("(longitude BETWEEN $min_lon AND $max_lon)");

所以它将被渲染为where (latitude BETWEEN $min_lat AND $max_lat) AND (longitude BETWEEN $min_lon AND $max_lon)并希望这将解决问题。

甚至不需要引用。

于 2012-06-15T11:32:08.780 回答
0
$this->CI->db->where("latitude BETWEEN '$min_lat' AND '$max_lat'");
$this->CI->db->where("longitude BETWEEN '$min_lon' AND '$max_lon'")

去掉简单的'

$this->CI->db->where("latitude BETWEEN $min_lat AND $max_lat");
$this->CI->db->where("longitude BETWEEN $min_lon AND $max_lon")
于 2012-06-14T12:20:54.870 回答