How can the RAND() function in MySQL be used to retrieve random rows efficiently in PHP?

When using the RAND() function in MySQL to retrieve random rows efficiently in PHP, it is important to use a combination of ORDER BY RAND() and LIMIT to prevent performance issues with large datasets. By ordering the results randomly and limiting the number of rows returned, you can efficiently retrieve random rows without causing excessive strain on the database.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Query to retrieve 5 random rows from the 'table' table
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 5";

// Execute the query
$result = $mysqli->query($query);

// Loop through the results
while ($row = $result->fetch_assoc()) {
    // Process each row as needed
    echo $row['column_name'] . "<br>";
}

// Close the connection
$mysqli->close();