Raman Saluja
Raman Saluja

Reputation: 106

how to use order by random in codeigniter

While Searching I want to show the paid customers firstly, and then rest of customers list

but the problem is I want to show by random for Example. paid customers should not mix with others. Can anyone tell what will be query?

please help me! I am using codeigniter

Upvotes: 1

Views: 5003

Answers (3)

Praveen Kumar
Praveen Kumar

Reputation: 2408

Mysql query for your need if i understood well

SELECT `featured`,group_concat(`id` order by rand() ) as `id` FROM `dbc_posts` where `status` = 1 GROUP By `featured` ORDER BY `featured` DESC

now with php

 $results  =  $this->db->query("SELECT `featured`,group_concat(`id` order by rand() ) as `id` FROM `dbc_posts` where `status` = 1 GROUP By `featured`  ORDER BY `featured` DESC")->result_array(); 

    $paid = $results[0];//featured = 1

    // comma seprated ids of the paid people e.g :- 3,7,1,26,92  are available in 
    $paidusers = $results[0]["id"];
    //seprate them by 
    $paidusers = explode(",",$paidusers);

    foreach($paidusers as $paiduser)
    {
        $row  =  $this->db->get_where("dbc_posts", array("id"=> $paiduser))->row();
        print_r($row );
        echo "<br>";
    }
     // do same for unpaid 
        $unpaid = $results[1];//featured = 0
    $unpaidusers = $results[1]["id"];
    //seprate them by 
    $unpaidusers = explode(",",$unpaidusers);

    foreach($unpaidusers as $unpaiduser)
    {
        $row  =  $this->db->get_where("dbc_posts", array("id"=> $unpaiduser))->row();
        print_r($row );
        echo "<br>";
    }

Ask me if anything goes wrong

Upvotes: 1

Sharmistha Das
Sharmistha Das

Reputation: 175

Set featured = 1 for paid and featured = 0 for unpaid customers in database. Then use the query mysql_query("SELECT * FROM dbc_posts WHERE status = 1 ORDER BY featured DESC, RAND() LIMIT 1");

Upvotes: 1

Zuber Mafat
Zuber Mafat

Reputation: 129

 Example:
 function randomval()
 {
      $this->db->order_by('id', 'RANDOM');
      $this->db->limit(1);
      $query = $this->db->get('tblname');
      return $query->result_array();

 }

Upvotes: 3

Related Questions