FORUMS CLOSED DUE TO SPAM. YOU STILL CAN ADD POST!

random article

Feed 7 posts, 3 voices

Avatar
19 posts

Hi all ,
This is my problem, select random an article from DB, i’ve read the source of page.php ….

  1. please forgive me, i have that shortcutted kind of code writing ##

but cannot understand the use of the object for the DB query .

anyone can help ?
Thanks
Matteo

 
Avatar
19 posts

up :)

I thought that i can do this by simply play with array but i think is bettere to do this via database instructions.

so i’m here to know :P

 
Avatar
316 posts

Why not use a combination of the find routine and a random number generator to choose “randomly” a mysql row?

 
Avatar
1493 posts

OK. Thought I’d try to contribute something useful for a change! :)

Here’s what I did: first, googled! And found an article on randomizing an array in PHP. That gave me the basis for the following:

  • create a hidden page as child-of-homepage called “Random Article”; since I use the cache plugin, I needed to set the “Is cacheable” drop-down to no;
  • as the content of this new “Random Article” page, I used this code:
<?php $randomArticles = $this->find('/articles/');
  $value = $randomArticles->children(array());
  $rand_key=array_rand($value,2);
  $randArticle = $value[$rand_key[0]];

  echo "<h4>".$randArticle->title()."</h4>";
  if ($randArticle->hasContent('extended')) { 
    echo $randArticle->content('body'); echo $randArticle->content('extended'); 
    } else {
    echo $randArticle->content();
  } 
  echo "<p><em>Permanent link</em>: ".$randArticle->link()."</p>";
?>

  • on my Homepage, I added this little link underneath the “recent articles” list:

Or read a <a href="<?php echo URL_PUBLIC; ?>random-article">random article</a>!

Done! You can see the results if you like. The Random Article code above doesn’t include comments, but you could include that if you like. Or readers can click the “Permanent link” to get the full picture.

There are probably other more elegant, more random ways of doing this. But for “quick-and-dirty”, I hope that’s a help. (Plus: more info on array_rand here.)

 
Avatar
19 posts

mhm the David answer is interesting and very near what i’de like to know.

But the question is/was how to use :

children(array(‘limit’ => 6, ‘offset’ => 0, ‘rand’ => ‘position ASC’))

with the MySQL RAND function

 
Avatar
1493 posts

Sorry, Matteo. I thought the question was how to “select random an article from DB” — someone else will have to help you with the more specific question! :)