Wednesday, November 3, 2010

Simple php code for Displaying Quotes in Random colors


In my previous post, I have listed lot of Barack Obama's Quotes collected from various sources.

You can see that each quote is appearing in random color. I have done everything within few minutes.

I will explain the simple steps I followed to do this in short time.

- First, I have collected Obama's quotes from various sources and put in in a simple plain text file.

- Then, created a mySql table named "quotes" with two fields "id" and "quotes". The sql will as below.


CREATE TABLE quotes (
id bigint(20) NOT NULL auto_increment,
quotes text NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY id (id)
)


- And then, clicked "Insert data from a textfile into table" in phpmyAdmin to import the text file into the "Quotes" table.

Now all the Quotes are inserted into the table "quotes".

- I created a php file "config.php" for keeping the details (hostname, username, password, dbname) required for connecting with mysql database table.

- Then, I created a php file "index.php" with below piece of code.


<?php
include ("config.php");

$sql_quotes="select quotes from quotes";
$query_quotes=mysql_query($sql_quotes);

while($row=mysql_fetch_assoc($query_quotes))
{

$color=random_color();

echo '<div style="padding-bottom:25px;font-weight:600;text-indent:25px;color:'.$color.'">'.$row["quotes"].'</div>';

}



function random_color(){
mt_srand((double)microtime()*1000000);
$c = '';
while(strlen($c)<6){
$c .= sprintf("%02X", mt_rand(0, 255));
}
return $c;
}


?>



- Just copied the output of this script and pasted it in the blog post.

If you want use two colors alternatively instead of using random color, you can use below piece of code.


include ("config.php");

$sql_quotes="select quotes from quotes";
$query_quotes=mysql_query($sql_quotes);
$i=0;

while($row=mysql_fetch_assoc($query_quotes))
{
if(($i%2)==0)
{
$color=random_color();
}
else
{
$color=random_color();
}
echo '<div style="padding-bottom:25px;font-weight:600;text-indent:25px;color:'.$color.'">'.$row["quotes"].'</div>';
$i ++ ;
}

The random color code needs to be improved further. Because, the current code won't give any guarantee that the consecutive colors are unique.

We can improve it further by adding a piece of code which will check the uniqueness of the consecutive colors.


Note:I used our html encode tool for putting this sample code in this blogger blog.

More Articles...
You can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:

Search This Blog