PDA

View Full Version : Random Selection through PHP



Diversions
08-19-2008, 07:46 PM
I am setting up a website in which I want to have a series of lines randomly selected from a PHP file.
For Example: productsrecap.php contains 60 items. What I want to do is to have 5 of those products randomly displayed on the html page.

Is such a thing possible? I am using W3C Schools to learn this stuff as I have dumped Front Page but I don't see anything that would resemble such a process. Just for the record - not quite yet up to speed on sql as yet if that is the answer to this.

Thanks for your help.

D

motormichael12
08-20-2008, 02:38 AM
$line = file('http://example.com/productsrecap.php');

if(!is_array($line)) die("File could not be opened");

$lines = explode("\n", $line);
$count = count($lines);

$item1 = rand(0, $count);
$item2 = rand(0, $count);
$item3 = rand(0, $count);
$item4 = rand(0, $count);
$item5 = rand(0, $count);

echo $lines[$item1];
echo $lines[$item2];
echo $lines[$item3];
echo $lines[$item4];
echo $lines[$item5];



I'm sure theres a better way and I'm not even sure that will work, but that is a quick attempt.

Diversions
08-20-2008, 12:47 PM
I'm sure theres a better way and I'm not even sure that will work, but that is a quick attempt.

It is much closer than I would have gotten. I will give it a go and work with the concept over the next few days and let you know how it turns out. Thanks for your help on this one.

D

jr_yeo
08-20-2008, 02:35 PM
select * from tablename order by rand();

techietim
08-20-2008, 03:03 PM
I'm sure theres a better way and I'm not even sure that will work

http://php.net/array_rand

motormichael12
08-20-2008, 03:17 PM
I am always learning more, and that right there is something I wish I would have learned alot sooner. That function looks extremely useful.

Diversions
08-20-2008, 03:42 PM
I am always learning more, and that right there is something I wish I would have learned alot sooner. That function looks extremely useful.

In my frontpage days, it is something I wanted to accomplish but never could, so it was one of those things that, as I sucked up my courage to do html and php properly, was at the top of the list to utilize as much php code as possible simply due to its versatility.

Thank you all for the information. It is extremely valuable and has also pointed me in the direction of an abundance of PHP coding.

D

jr_yeo
08-23-2008, 02:54 AM
you're welcome.