Creating a random link generator
The random generator code that this generator uses was originally posted to the PHP mailing list. View the original: Retrieve random Sql results
SQL for links table:
# Table structure for database table 'links'
#
CREATE TABLE links (
id tinyint(5) DEFAULT '0' NOT NULL auto_increment,
name char(250) NOT NULL,
url char(250) NOT NULL,
alt char(250) NOT NULL,
PRIMARY KEY (id)
);
PHP Code:
<?php $db = mysql_connect("server", "username", "password"); mysql_select_db("database",$db) or die ("Unable to connect to database"); [Rember to enter the name of your server, your username, your password and the name of the database you are connecting to.] // Seed random number generator. srand((double)microtime()*1000000); $query= mysql_query("SELECT * FROM links where 1=1"); // Get number of rows returned. $rows_found = mysql_num_rows($query); if($rows_found > 0) { // Generate a random number up to the number of records returned $rand_row = rand(1, $rows_found); // Seek to randomly chosen record and get it's contents. mysql_data_seek($query, $rand_row - 1); $row = mysql_fetch_array($query); // Do stuff with randomly chosen row here... $link_name=$row["name"]; $url=$row["url"]; $id=$row["id"]; $alt=$row["alt"]; // Print a random link printf("<p><a href="%s" alt="%s">%s </a><br>n",$url,$alt,$link_name); } ?>