Kevin Jung
Kevin Jung

Reputation: 3103

shuffling from an array with mysql

I need some help here.

I have a mysql table called dictionary like this:

id  word
1 test
2 hello
4 bye
7 werd

In php, I want to query the db so that I can get an array of the id field

so the array would list 1 2 4 7.

With this array, I want to run the array_rand function in php so I can get a random number from 1 2 4 7.

Can someone show me the proper mysql query to list the id field and return it into php as an array? and how I could run that array with random array function.

Upvotes: 2

Views: 835

Answers (3)

publikz.com
publikz.com

Reputation: 961

No need shuffle this in php, - effective is to

use "SELECT id FROM table ORDER BY rand();"

than take all records and store id into array ...

Upvotes: 3

Mikecito
Mikecito

Reputation: 2063

If you plan on using the random row and then querying for another, I would just randomize on the MySQL query. Get a count of the rows in the table, create a random integer somewhere between 0 and that count, and then use LIMIT in your MySQL query to return a random row.

If you plan on keeping it all in memory, then David's answer would work better.

Upvotes: 0

David Fells
David Fells

Reputation: 6798

Use the shuffle function

Upvotes: 1

Related Questions