Displaying Random Links

This tutorial goes out to Andre who wanted to use the URL Rotator for something similar but different. In this tutorial I am going to assume that you already have a database table “textlinks” set up with at least the following fields: title, url

The Code

$global_dbh = mysql_connect("localhost","dbusername","dbpassword");
mysql_select_db("dbname", $global_dbh);

$query = "SELECT `title`, `url` FROM `textlinks` ORDER BY RAND() LIMIT 10";
$result = mysql_query($query, $global_dbh);
$cnt = mysql_num_rows($result);

for ($i=0; $i<$cnt; $i++) {
$row = mysql_fetch_row($result);
echo "<a href='$row[1]' target='_blank'>$row[0]<br />";

This is fairly simple, however it is put in the “Advanced” section of the tutorials as the “Basic” will be just syntax and the very basics.

The first paragraph we connect to the database. Remember to change dbusername, dbpassword, and dbname to your username, password, and database name.

The second paragraph is the key MySQL command. ORDER BY RAND() tells it to randomly pick them. LIMIT 10 tells it to limit the results to 10 rows.

The third paragraph just goes through all the rows, and outputs the links. If you prefer to use $row[“title”] and $row[“url”] change mysql_fetch_row to mysql_fetch_array.

So there you have it! Any questions?