WebNovice
WebNovice

Reputation: 2220

How can I randomize database rows if i am using mysql objects - codeigniter

My model returns data as mysql objects:

return $q->result();

Now, I want to shuffle/randomize the data and send it to the view file. But when I use the shuffle($data) on the object, it doesn't work, gives out an error. I guess, it will only work if my model returns an array.

Is there any way I can shuffle/randomize the data without converting it to an array, or without making the model return an array.

Upvotes: 1

Views: 1787

Answers (4)

flykobe
flykobe

Reputation: 135

In mysql, you can order rows with order by rand(), like this:

select product_id  from product order by rand() limit 10;

so, you can get appropriate number of rows you want.

EDIT:

@Damchey you're right. If the table is bigger, than the rand() function will be slow. But every time, how many rows you select? So, Maybe you can get a random offset in php, and sql will like this:

select product_id  from product offset $random_offset limit 10

Although, the order of product_id is same, but offset is different, so if your table is big, than everytime you can get different rows. And make sure, your offset if not bigger than rows_total - limit_num .

Upvotes: 0

Francois Deschenes
Francois Deschenes

Reputation: 24989

Have you thought about add $this->db->order_by('id', 'random'); when generating the query? The first parameter is the field name and the second the order (possible values are "asc", "desc", and "random"). Have a look at the order_by function for more information.

EDIT:

Alternatively, you could use result_array() instead of results(). Here's an example:

// PHP5
$shuffled_result = $this->db->get('table')->result_array();
shuffle($shuffled_result);

// PHP4
$query = $this->db->get('table');
$shuffled_result = $query->result_array();
shuffle($shuffled_result);

Upvotes: 4

TreantBG
TreantBG

Reputation: 1222

Well make you model to return the mysql data as array (give me the code if you don't know how) and from then you can use to shuffle the array with Shuffle function

I don't think you can shuffle the data base it self with query or something

Upvotes: 0

alex
alex

Reputation: 490453

Objects do not have any explicit order of properties. You should be using an array if you require ordering.

Upvotes: 1

Related Questions