03-Apr-2023
.
Admin
Hi Dev,
This tutorial is focused on how to select random row from table in php mysql. This post will give you simple example of return random rows from a mysql table using php. this example will help you mysql select random records. you will learn display a random row from a database in php with mysql. follow bellow step for mysql get random row with code examples.
To select a random row, use the rand() with LIMIT from MySQL.
Example :
index.php
$sql = CREATE TABLE employee (
id int NOT NULL AUTO_INCREMENT,
Name varchar(20),
Age int,
PRIMARY KEY(Id)
);
Insert some records in the table using insert command :
$sql = INSERT INTO employee(Name, Age) VALUES('David', 21);
$sql = INSERT INTO employee(Name, Age) VALUES('Uday', 20);
$sql = INSERT INTO employee(Name, Age) VALUES('Sam', 26);
Display all records from the table using select statement :
select * from employee;
Output:
+----+----------+-------+
| Id | Name | Age |
+----+----------+-------+
| 1 | David | 21 |
| 2 | Uday | 20 |
| 3 | Sam | 26 |
+----+----------+-------+
Here is the query to select a random row from the table using rand(). The query is as follows:
select * from employee order by rand() limit 1;
Output:
+----+------+------+
| Id | Name | Age |
+----+------+------+
| 2 | Uday | 20 |
+----+------+------+
I hope it could help you...
#PHP