Re: display query results at random

From: Date: Wed, 26 Sep 2001 12:51:06 +0000
Subject: Re: display query results at random
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-68846@lists.php.net to get a copy of this message
"Matthew Delmarter" <matt@adplusonline.com> wrote: > How do I return a specific record from a db outside of the query? > > Let's say I "select * from table" (using mysql_fetch_object) and get 5 > results. I want to display the 5 results in different / random places > on the page. > > Place 1 - show details for record 3 > Place 2 - show details for record 1 > Place 5 - show details for record 5 > > How do I do this? Someone mentioned saving to an array. That's the way to go, but I'm not sure if the reply was clear. $i = 1; while ( $qd= mysql_fetch_object( $rs ) ) { if ( $i == 1 ) { $var1 = $qd->my_field; } else if ( $i == 2 ) { $var2 = $qd->my_field; } ... else if ( $i == 5 ) { $var5 = $qd->my_field; } } Then use $var1, $var2, ..., $var5 where needed after the loop finishes. I may be misunderstanding, so if you really want your query to return 5 records, but want to randomly pick a record for each of 5 random spots on your page then do this: $i = 1; while ( $qd= mysql_fetch_object( $rs ) ) { $var[] = $qd->my_field; $i++; } Then use array_rand() inside a loop to pull from $var[], removing each element after it's selected (more efficient) or adding code to ensure the same element isn't picked twice (less efficient). -- Steve Werby President, Befriend Internet Services LLC http://www.befriend.com/

« previous php.general (#68846) next »