We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,721 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

I Wanna Change This Random Code

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>';
    }
7
Contributors
5
Replies
1 Week
Discussion Span
10 Months Ago
Last Updated
6
Views
dani0
Newbie Poster
5 posts since Sep 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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
pritaeas
Posting Prodigy
Moderator
9,265 posts since Jul 2006
Reputation Points: 1,173
Solved Threads: 1,456
Skill Endorsements: 86

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.

cereal
Veteran Poster
1,144 posts since Aug 2007
Reputation Points: 344
Solved Threads: 222
Skill Endorsements: 22

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

dani0
Newbie Poster
5 posts since Sep 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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

Low Platelets
Newbie Poster
1 post since Jul 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 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.

vibhaJ
Posting Shark
958 posts since Apr 2010
Reputation Points: 161
Solved Threads: 190
Skill Endorsements: 3

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0742 seconds using 2.69MB