1.11M Members

I Wanna Change This Random Code

 
0
 

Hi,

I want to change this code as given 1 result. I don't need 10 line results. I just need 1 line result. When I tried to change 10 with 1 it doesn't work. Please help me about that.

    while( $row = mysql_fetch_array($query) )
    {
        $id[] = $row['id'];
    }

    $id = array_flip($id); 
    $random_id = array_rand($id, 10); 
    $random_id = implode(',',$random_id);

    $sql1 = 'SELECT * FROM table WHERE id IN(' .$random_id. ')';
    $query1 = mysql_query($sql1);

    while( $row1 = mysql_fetch_array($query1) )
    {
        echo $row1['name'].'<br>';
    }
 
1
 

Instead of looping through all results and then picking a random one, you can let MySQL do the job:

SELECT * FROM table ORDER BY RAND() LIMIT 1
 
0
 

If I understood you can also replace previous $random_id array_rand() and implode() with:

$random_id = shuffle($id); # or you can use array_rand($id,1);
$sql1 = "SELECT * FROM table WHERE id = '$random_id[0]'";

and if you want one single result from the query then add limit 1 at the end, bye.

 
0
 

pritaeas, Yes you are right. But I just wanna try different codes.
cereal, It works.
Thank you very much guys.

 
0
 

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Alena

 
0
 

ORDER BY RAND()

ORDER BY RAND() will do the same thing.
Better to use it instead of 4 line coding. For better practice when things are possible from mysql query better to use it directly instead of 2-3 php operation.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: