Jump to content

How to make a while loops without dublicate?


Incredinot

Recommended Posts

Hi..

 

Okay, so i want to make a while loops that graps 3 things randomly.

 

But how do i make sure that it dont print out the same?

 

In my test i have the numbers from 1 to 10.

 

When i make this while loop, it works just fine and print out 3 values..

 

My problem tho is that it sometimes print "1 1 4" instead of "3 7 2" (or something like that)

 

$i = 1;
while ($i <= 3) {

$this = mysql_query("SELECT nid FROM xx WHERE type='xx' ORDER BY RAND()");
$that = mysql_fetch_array($this);

// Random ID.
$id = $that['nid'];

print $id;

}

Hmm, that dont work...

 

Am i doing something wrong?

 

<?php 

$i = 1;
while ($i <= 3) {

$var1 = mysql_query("SELECT DISTINCT nid FROM xx WHERE type='xx' ORDER BY RAND()");
$var2 = mysql_fetch_array($var1);

$id = $var2['nid'];

?>

<table width="294" height="26" border="0">
  <tr>
    <td width="95" align="left" valign="top"><?php print $id; ?></td>
  </tr>
  </table>
  
  <?php 

$i++;
}
?>

It does not work as you expect because you're doing a select statement inside the loop, so you're getting the same result each time you loop.  You'll want to get the data you want outside of the loop, then run the results inside the loop.

 

Not tested...

 

<?php 
$id_string = ''; //variable to hold concatenated IDs

$result= mysql_query("SELECT DISTINCT nid FROM xx WHERE type='xx' ORDER BY RAND() LIMIT 3"); //get the distinct results limited by 3 rows of data

//loop each one
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $id_string .= $row['nid'];//put the value from the database into my string variable
}

?>

<table width="294" height="26" border="0">
  <tr>
    <td width="95" align="left" valign="top"><?php print $id_string; ?></td>
  </tr>
  </table>
  
  <?php 

$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.