GregHBushnell GregHBushnell - 1 month ago 5x
HTML Question

php mysql random rows no duplicates

Hi im trying to get 5 random rows from a database and then display them. i currently do this but it does result in duplicates.

i need to change the limit to 5 and then store them in an array but how do i do that? or is there a better way?

function GetPlayer($link){
if (isset($_SESSION['username'])) {
$x = 0;
while($x <= 5) {
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 1; ";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($result);
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
echo ("<tr>");
echo ("<th>".$row['username']." </th>");
echo ("<th>Level: ".$row['Level']." </th>");
echo ("<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>");
echo ("<th>Win Chance: ");
echo CalculateWinChance($link,$row['Defence']);
echo ("<th><input type ='submit' name = 'Attack_Btn' value ='Attack'></th>");
echo ("</tr>");


Why dont't you try to request 5 results (LIMIT 5) AND loop this? It will no return any duplicates. Four queries less would be a side effect.

$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
while($row = mysqli_fetch_assoc($result)){