【问题标题】:Codeigniter: Better way to select db?Codeigniter:选择数据库的更好方法?
【发布时间】:2011-01-05 22:32:12
【问题描述】:

这是我从 SQL 数据库中获取内容的函数...

有没有更优雅的方法来做到这一点?

function getResults_1($id)
{
    $this->db->select(array("a_1","a_2"))->from('Survey');
    $this->db->where('user_id', $id);

    return $this->db->get();
}
function getResults_2($id)
{
    $this->db->select(array("a_6","a_8","a_13","a_14"))->from('Survey');
    $this->db->where('user_id', $id);

    return $this->db->get();
}
and so on... (to 5)...

【问题讨论】:

    标签: php select codeigniter


    【解决方案1】:

    @Steven 结果的更优化(对于初学者来说可能更复杂)版本。这假设您没有超出数组索引引用的范围,否则会出错。

    function get_results($id, $method) {
        $select_cols = array(1 => array('a_1','a_2'),
                             2 => array('a_6','a_8','a_13','a_14'));
        return $this->db->select($select_cols[$method])
                        ->where('user_id', $id)
                        ->get('Survey');
    }
    

    【讨论】:

      【解决方案2】:
      function get_results($id, $method) {
          switch($method) {
              case 1: $select = array('a_1','a_2'); break;
              case 2: $select = array('a_6','a_8','a_13','a_14'); break;
              default: $select = false;
          }
      
          if($select) $this->db->select($select);
          $this->db->where('user_id',$id);
      
          return $this->db->get('Survey');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-18
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 2018-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多