选择最接近变量的值

时间:2013-10-04 11:52:26

标签: php mysql codeigniter

我正在尝试运行一个函数,该函数在数据库表中查询最接近变量mba_score的数值$runscore。我的功能看起来像这样:

public function get_player($runscore)
{
   $per = $this
             ->db
         ->select('mba_id, abs($runscore - mba_score) as mba_rate', FALSE)
         ->order_by('mba_rate', 'ASC')
         ->get('nba_scores');
         ->limit(1);

        if ($per->num_rows > 0) {
            $p = $per->row_array();
            return $p['nba_id'];
        }
        return false;           
        }

我得到的错误是:

"Error Number: 1054

Unknown column '$runscore' in 'field list'"

我尝试过多次编写和重写这段,并且无法获得结果。

3 个答案:

答案 0 :(得分:2)

使用双引号:

select("mba_id, abs($runscore - mba_score) as mba_rate", FALSE)

使用单引号,变量$ runscore不会替换为其值。如果要使用单引号,则应使用连接:

select('mba_id, abs('.$runscore.' - mba_score) as mba_rate', FALSE)

答案 1 :(得分:1)

变化:

->select("mba_id, abs($runscore - mba_score) as mba_rate", FALSE) //use doube quote

答案 2 :(得分:0)

您应该在变量中使用

 ->select("mba_id, abs('".$runscore."' - mba_score) as mba_rate", FALSE)
         ->order_by('mba_rate', 'ASC')
         ->get('nba_scores');
         ->limit(1);