Jump to content

While Loop, Order By Rand()


alalj23

Recommended Posts

I'm trying to display 3 results from my table ordered by random. I understand that ORDER BY RAND () is not the most efficient way to do this but I will worry about that later. I get output from the code below but it is the same name three times. Each time I reload it is a different name, but still just the same name three times. Where am I going wrong?

 

 

<?php

include_once 'header.php';

$con = mysql_connect("localhost","*****","******");

mysql_select_db("cards",$con);

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

$sql = "SELECT * FROM cards ORDER BY RAND() LIMIT 3";

$results = mysql_query($sql);

$array = mysql_fetch_array($results);

$num=mysql_num_rows($results);

$i=0;

while ($i < $num) {

echo $array['playerName'];

$i++;

}

include_once 'footer.php';

?>

Link to comment
https://forums.phpfreaks.com/topic/271504-while-loop-order-by-rand/
Share on other sites

$array = mysql_fetch_array($results);
$num=mysql_num_rows($results);
$i=0;
while ($i < $num) {
 echo $array['playerName'];
 $i++;
}

 

You are only fetching the first row. Try

 

$num=mysql_num_rows($results);
$i=0;
while ($i < $num) {
 $array = mysql_fetch_array($results); # <== Fetch a row of data
 echo $array['playerName'];
 $i++;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.