Hi, im building a site and i have a "news" column. My idea is to have for example a php file where i can write 5 news and upload the file so everytime somebody enters the site, he can read one of those five news. This could be random, you enter the site, you get one news... Is there a way to do this? Thanks, fuser
If the news is stored in MySQL database you can do this: $sql = "SELECT * FROM news_table ORDER BY RAND() LIMIT 1"; PHP:
Hi, thanks for the help.. its not info from the database. What i need is a script or html file that i can modify/upload and the news section in the index will change and will be random. For example, there are some ad rotator scripts where you put the code on a php file for 5 banners and then they are shown randomly on the site.. Hope somebody can help me.. Thanks, fuser
It is very easy to fetch 1 row on random from the table. $random = rand(1,4); // Where 4 is the max it can go as we have 5 results. $sql = mysql_query("Select * from table_news LIMIT $random, 1");
If you are using HTML in the examples, it may just be easier to put each one in its own file and just use file_get_contents() on the one you use, else you could just store it in strings. Approach 1 - Files - Will be a little slower and more intensive. Create a directory called banners, and in it put all your HTML banner files. In your PHP, make a list of all your files, and select one at random. <?php $files = array('banner1.htm','banner2.htm'); //A list of all your files in the 'banners' directory. $randomFile = rand(0, 1); //The first number of rand(0,1) must be 0. The second number is the amount of files you have, minus 1. $banner = file_get_contents('banners/'.$files[$randomFile]); //Include a random file echo $banner; ?> PHP: Approach 2 - Strings Same basic gist, just screw making extra files and directories: <?php $files = array('<b>A News item</b>', '<a href="news.html">Another News item</a>' ); //The content of all your news items. $randomString = rand(0, 1); //The first number of rand(0,1) must be 0. The second number is the amount of strings you have, minus 1. $banner = $strings[$randomString]; ?> PHP: