2

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() ); } 
0

3 Answers 3

1

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; } 
Sign up to request clarification or add additional context in comments.

Comments

0

Add following in your query

 $this->order_by('posted_date', 'desc'); 

So your final query would be

$this->db->select($fields); $this->db->get_where(self::$tbl_name, array( "user_id" => $volunteer_id)); $this->order_by('posted_date', 'desc'); $query=$this->db->get(); return $query->result(); 

3 Comments

Call to undefined method Volunteer_notes::order_by().. i got this error message
Refer codeigniter's reference guide for details ellislab.com/codeigniter/user-guide/database/… -> $this->db->order_by();
Calling get_where() then order_by() then get() reveals a lack of understanding in CodeIgniter's active record methods.
0
  • Option parameters are logically written after required parameters ($volunteer_id before $select) so that parameters can be omitted at the call site.
  • Active record methods are designed for chaining; enjoy that elegance.
  • When building a query, the method calls don't need to be in clause order, but the query will be executed in its current state when get() or get_where() (and a few other methods) are called.
public function getByVolunteerId( int $volunteerId, array|string $fields = '*' ): array { return $this->db ->select($fields) ->order_by('posted_date', 'desc') ->get_where( self::$tbl_name, ['user_id' => $volunteerId] ) ->result(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.