In MySQL, this is probably the easiest thing to do in two queries. First get the number of rows in the table:
SELECT COUNT(*) FROM MyTable;
Then prepare the query to get random strings:
SELECT ... FROM MyTable ORDER BY RAND() LIMIT ?;
Then execute the prepared request and send the counter value divided by 10.
Not every problem should be solved in one request.
Here is an example PHP script edited to use the old mysql extension.
<?php // Get the total number of rows in the table. $sql = "SELECT COUNT(*) FROM Kingdoms"; $result = mysql_query($sql); $row = mysql_fetch_array($result); $rows_in_table = $row[0]; // We only want a portion of the rows, specified by the user // choice of percentage. The count we want is therefore equal // to the total number of rows in the table multiplied by the // desired percentage. $percentage = intval($_GET["percentage"]) / 100.0; $count = intval(round($rows_in_table * $percentage)); // LIMIT makes the query return at most the number of rows specified. // Sort randomly first (if the table has too many rows this will be slow), // then return the first $count rows. $sql = "SELECT * FROM Kingdoms ORDER BY RAND() LIMIT {$count}"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result)) { print_r($row); }
PS: Always be careful when interpolating a variable into an SQL expression. You have to force the variable to a known format - an integer value in this case. Otherwise, you risk creating a SQL Injection vulnerability.
source share