CodeIgniter之Model中的查询语句

方式一:使用$this->db->query('sql查询语句');

示例1单表查询


 function selectUserByName($name){
<!-- lang: php -->
        $query = $this->db->query('select id,qq,email,address from user where name = "'.$name.'"');
<!-- lang: php -->
        return $query->result_array();
<!-- lang: php -->
}

示例2单表多条件查询:


function selectInfo($productId,$userid){
<!-- lang: php -->
    $query = $this->db->query('select * from table1 where id !='.$productId.'and userid ='.$userid.' and isrecommand = 1'); 
<!-- lang: php -->
    return $quey->result_array();
<!-- lang: php -->
}

示例3按照日期排序,最新的排在前面:


public function selectInfo($var1,$var2){
<!-- lang: php -->

<!-- lang: php -->
    $query = $this->db->query('select id,col2,col3,last_update_date from table1 where col4 ='.$var1.'and col5 ='.$var2.'and col6 !="" order by last_update_date DESC' );
<!-- lang: php -->

<!-- lang: php -->
    return $query->result_array();
<!-- lang: php -->
}

示例4联合查询:


    function selectInfo($productId){
<!-- lang: php -->
    $query = $this->db->query('select * from table1 join ptable2 on table2.productextid=table1.id where table2.productid='.$productId);
<!-- lang: php -->
    return $query->result_array();
<!-- lang: php -->
}

方式二:使用CodeIgniter提供的语句

$this->db->select('要查询的字段名1[,要查询的字段名2[,要查询的字段名3[,……]]]');

$this->db->where(“字段名”,该字段的值);//该语句可以出现多次

$this->db->get(“表名”);//并返回查询的结果,通常用变量$query来接收

示例5:


public function getInfo($var1){
<!-- lang: php -->
    $this->db->select("col1");
<!-- lang: php -->
    $this->db->where("col2",$var1);
<!-- lang: php -->
    $query = $this->db->get("table1");
<!-- lang: php -->
    retrun $query->result_array();
<!-- lang: php -->
}

该种方式的详细语句参见:http://codeigniter.org.cn/user_guide/database/active_record.html

你可能感兴趣的:(CodeIgniter之Model中的查询语句)