What SQL query can be used to randomly select a limited number of rows from a database table in PHP?

When you need to randomly select a limited number of rows from a database table in PHP, you can use the SQL query below. This query utilizes the RAND() function to generate a random number for each row, then orders the rows by this random number and limits the result to the desired number of rows.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Define the number of rows to select
$numRows = 5;

// SQL query to randomly select a limited number of rows
$sql = "SELECT * FROM your_table ORDER BY RAND() LIMIT $numRows";

// Execute the query
$stmt = $pdo->query($sql);

// Fetch the selected rows
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Output the selected rows
print_r($rows);