How to Return Random Rows From a MySQL Table Using PHP


In this article, we show how to return random rows from a MySQL table using PHP.

This can be useful for many purposes, such as if you want to check a random user or a random record.

To do this in MySQL, you use the built-in rand() function.

So the above is the MySQL code to return the rows of the table in random order.

We'll now show how to tie this in with PHP.

PHP Code

The PHP code to return the rows of a table in any random order is shown below.

So the following code gets the data required to make a connection to a database and actually selects a database.

We then create a variable named $result that selects the table, table_name, and orders it in random order using the built-in MySQL rand() function.

You then can later decide what you want to do with these selected rows.

I created a MySQL table called PopularToys. This is shown below.

MySQL PopularToys table

Applying the PHP code above and displaying the rows in tabular form, the following result is achieved.

Actual PHP Output