Jump to content

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';

?>

Edited by alalj23
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++;
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.