如何在mysql查询中执行php函数

时间:2013-11-19 20:52:00

标签: php mysql codeigniter

function SearchMembers()
{
    // grab user input
    //$my_gender = $this->security->xss_clean($this->input->post('my_gender'));
    $this->security->xss_clean($this->input->post('looking_for_gender'));
    $age_from = $this->security->xss_clean($this->input->post('age_from'));
    $age_to = $this->security->xss_clean($this->input->post('age_to'));
    $member_postcode = $this->security->xss_clean($this->input->post('postcode'));
    $member_distance = $this->security->xss_clean($this->input->post('distance'));                               

    // Prep the query

    $this->db->where('Gender', $looking_for_gender);
    $this->db->where('Age >=', $age_from);
    $this->db->where('Age <=', $age_to);
    $miles =  $this->search_form_model->distCalc('postcode',$member_postcode);
    $this->db->where($miles < $member_distance);
    // Run the query
    $query = $this->db->get('member');
    // Let's check if there are any results

    if ($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
        {
            return $query->result();
        }

        // If the previous process did not validate
        // then return false.
        return false;
    }
}

希望有人可以提供帮助。我正在以英里为单位执行两个邮政编码之间的距离检查,并添加距离结果不到距离的所有邮政编码。

以前我所做的就是遍历所有匹配性别和年龄的邮政编码,然后比距离检查少了几英里但结果是json数组,现在想要在mysql查询中执行它,如果可能的话,理想情况下使用codeigniter框架。非常感谢

1 个答案:

答案 0 :(得分:0)

首先,使用绑定参数而不是XSS clean:

请参阅Does CodeIgniter automatically prevent SQL injection?

假设你有经度和纬度,你可以添加它来选择距离

$this->db->select("
            Gender,Age, --etc.
            (
                (
                    ACOS(
                          SIN($lat * PI() / 180) 
                        * SIN(`lat` * PI() / 180) 
                        + COS($lat * PI() / 180) 
                        * COS(`lat` * PI() / 180) 
                        * COS(($lon - `lon`) 
                        * PI() / 180)) 
                        * 180 / PI()
                ) * 60 * 1.1515
            ) AS distance            
        ");

您还需要order by进行排序,having只能返回距离内的值。

$this->db->order_by('distance');
$this->db->having('distance <= '.$member_distance.' OR postcode='.$member_postcode);