MySql tutorial: display random data from your database

Hi guys! In this tutorial I want to speak about MySql. In this tutorial I will explain how is possible to display random data from a database.

I have writed a simple sql code

$db1 = mysql_connect("localhost","user","");
mysql_select_db("test2",$db1);

$count = mysql_query("SELECT * FROM `article`");
$c = mysql_num_rows($count);
$rand = rand(3, $c) - 3;
$get = mysql_query("SELECT * FROM `article` WHERE `id` > '$rand' LIMIT 3");
while($show = mysql_fetch_array($get)):
echo $show["text"]."
";
endwhile;

and now I will explain how it works.

$count = mysql_query("SELECT * FROM `article`");
$c = mysql_num_rows($count);

this code will count how many rows exist in the table article.

$rand = rand(3, $c) - 3;

This function will display a random number less than the number of rows from the table `articles`.

$get = mysql_query("SELECT * FROM `article` WHERE `id` > '$rand' LIMIT 3");

this query will display data from the table `articles` where id is bigger than $rand.

Video tutorial:









Leave a Comment