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

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

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.

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.