Php random row help...

Posted by Skillman on Stack Overflow See other posts from Stack Overflow or by Skillman
Published on 2010-06-10T10:28:37Z Indexed on 2010/06/10 10:33 UTC
Read the original article Hit count: 139

Filed under:
|
|
|

I've created some code that will return a random row, (well, all the rows in a random order) But i'm assuming its VERY uneffiecent and is gonna be a problem in a big database...

Anyone know of a better way?

Here is my current code:

$count3 = 1;
$count4 = 1;
//Civilian stuff...
$query = ("SELECT * FROM `*Table Name*` ORDER BY `Id` ASC");
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$count = $count + 1;
$civilianid = $row['Id'];
$arrayofids[$count] = $civilianid;
//echo $arrayofids[$count];
}

while($alldone != true) {
$randomnum = (rand()%$count) + 1;
//echo $randomnum . "<br>";
//echo $arrayofids[$randomnum] . "<br>";
$currentuserid = $arrayofids[$randomnum];
$count3 += 1;

while($count4 < $count3) {
$count4 += 1;
$currentarrayid = $listdone[$count4];
//echo "<b>" . $currentarrayid . ":" . $currentuserid . "</b> ";
if ($currentarrayid == $currentuserid){
$found = true;
//echo " '" .$found. "' ";
}
}

if ($found == true) {
//Reset array/variables...
$count4 = 1;
$found = false;
} else {
$listdone[$count3] = $currentuserid;
//echo "<u>" . $count3 .";". $listdone[$count3] . "</u> ";
$query = ("SELECT * FROM `*Tablesname*` WHERE Id = '$currentuserid'");
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$username = $row['Username'];
echo $username . "<br>";
$count4 = 1;
$amountdone += 1;
if ($amountdone == $count) { //$count
$alldone = true;
}
}
}

Basically it will loop until its gets an id (randomly) that hasnt been chosen yet. -So the last username could take hours :P

Is this 'bad' code? :P :(

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql