phpcodeigniterselectactiverecordsql-order-by

How to add an ORDER BY clause to a CodeIgniter active record executed by get_where()?


I want to fetch the database data by descending order of posted date.Database containing a field named posted_date. This is my code (in my model) to fetch the data.

public function get_data_by_volunteer_id($fields = "*", $volunteer_id)
{
    $this->db->select($fields);
    $query = $this->db->get_where(self::$tbl_name, array(
        "user_id" => $volunteer_id));
    return( $query->result() );
}

Solution

  • You can try this

    function get_data_by_volunteer_id($fields, $volunteer_id)
    {
    
        $query = $this->db->query("SELECT * FROM table_name WHERE user_id = '$volunteer_id' ORDER BY posted_date DESC");
        $result = $query->result_array();
        return $result;
    
    }