Random Links and images with PHP & MySQL

script written by

Description:

This script allows any number of images to be referenced and have an associated hyperlink attached, which makes it great for 88x31 buttons which are commonplace throughout the web. The script requires a web server with PHP and a MySQL database to store the data.

Code:

Creating the database table.

		
// Code to create the table.

CREATE TABLE `links` (

  `id` int(11) NOT NULL auto_increment,
  `link` text NOT NULL,
  `image` longtext NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM;

Inserting the data with an SQL statement

// SQL statement to insert values into the database. (Add more if required)

insert into links values ('NULL',"http://www.site1.com", "path/image.gif", "website description");
insert into links values ('NULL',"http://www.site2.com", "path/image.gif", "website description");
insert into links values ('NULL',"http://www.site3.com", "path/image.gif", "website description");

The PHP Script

// PHP script
<?
// Connect to the database
mysql_connect ('localhost', 'username', 'password') ;
mysql_select_db ('database_name_here'); 

// Edit this number to however many links you want displaying
$num_displayed = 3 ;

// Select random rows from the database
$result = mysql_query ("SELECT * FROM links ORDER BY RAND() LIMIT $num_displayed"); 

// For all the rows that you selected
while ($row = mysql_fetch_array($result)) 

{
// Display them to the screen...

echo "<a href=\"" . $row["link"] . "\">
<img src=\"" . $row["image"] . "\" border=0 alt=\"" . $row["text"] . "\">
</a>" ;
}
?>

To use the script, either copy the code into your favourite text editor, or click here to download the files as a ZIP file.

Discuss in the forums



Remember, if you get stuck or need to ask any questions, register with the forums and tell us about it!

Partners Partners