Generate Random Quotes – A PHP Snippet

12 Dec, 2011  |  Written by  |  under MySQL, PHP

php-random-quote-generatorRandom Quotes… What do I mean by this? Simple, I mean creating a script that allows you to insert your choosen quotes into an MySQL Database and recall them at random displaying one at a time. When the page is refreshed, reloaded on a system the PHP Code would select from your inserted quotes and show one at random.

So, who would actually need something like this? There are many plugins out there to grab and use on your sites. So lets just say you do not use a Blogging Platform. You have a static website that you are looking at trying to change dynamically as a visitor first visits or revisits your site.

The simplest way of doing this would be to add things that change everytime a viewer comes to your site. This type of script could be changed to show at random pictures, actual site content, video links, customer comments. The ideas are endless and only your imagination will hold you back.

But first, you need the basic foundation that will allow you to build and further develop your idea. So this is basically what I am going to walk you through here. By the end of this blog post you will have a fully working code that will connect to a MySQL Database, allow you to save quotes, and also recall them at random on any page you desire.

Ok, lets get started. So, first you will need to create a database so we can add tables and content. So I will assume you have already got a database in place and you know the server, database name, username and password.

Now we have our database we need to decide what columns we need. So lets say we need an ID column, a quote column and the author of the quote column. So we will name our table ‘random_quote’, and we will have three columns within our table named: id, quote, author.

We need to create this data within our database so below you can copy the code into your query window of your PHPMyAdmin installation for ease of use:

CREATE TABLE `random_quote` (
`id` int(11) NOT NULL auto_increment,
`quote` varchar(255),
`author` varchar(50),
PRIMARY KEY  (`id`)
)

The simple code above will create a table called ‘random_quote’. Then the code will create a column called id which we have set to auto increment unless you specifically enter a number. Then we create a column called quote and another called author. Note the quote column has been limited to 255 characters and the author column has been limited to 50 characters. If you think you will require more character allowance then adjust as necessary. We also set the Primary Key to the id column as that will be how we are uniquely identifying our quotes.

We now have our table within our database so the next stage would be to create the code that will connect to our database. So I am sure from reading my other posts you have gotten a good idea of how to do this already but I will briefly go through the process here again just incase.

You need to save the below code into a file called connect.php:

$host = "your_host";
$user = "your_username";
$pass = "your_password";
$dbase = "your_database";
$db_connect = mysql_connect($host,$user,$pass);
@mysql_select_db($dbase) or die( "Unable to select database");

Our first four lines are defining variables that we use to connect to the database with on the next two lines. We then assign our mysql_connect() to another variable which actually handles the connection. Then our last line selects the correct database to connect to and if the code can not find the database or connect for any reason the error message is displayed on the screen. This page we will need to call later on so we can connect to the database easily.

Right, now we need a form so we can add quotes to the database we created. So lets code a really simple form to handle this for us. Create another page and call it save_quote.php:

<form action="" method="post">
<label for="quote">Enter Quote:</label>
<input type="text" name="quote" id="quote" maxlength="255" />
<label for="author">Enter Author:</label>
<input type="text" name="author" id="author" maxlength="50" />
<input type="submit" value="Save Quote" />
</form>

So you should recognise the code above as a simple form with an ‘action’ and the method ‘post’, labels and inputs then a submit. Simple stuff but if you are still unsure about anything within this form then you can always checkout the basics of HTML Coding by searching your second best friend Google. (your first would be me… :) you never know, if you get in contact with me I might just write you a tutorial for creating forms and sending the inputs via email or saving into a database).

Now we have to be able to grab the values entered into this form and save them to our newly created database. So lets have a look below at some code that will do this for us:

if ($_REQUEST['quote'] != "") {
    if($_REQUEST['author'] != "") {
        $author = $_REQUEST['author'];
    } else {
        $author = "Not Specified";
    }
    $quote = $_REQUEST['quote'];  

    $query = "INSERT INTO `random_quote` (`quote`,`author`) values ('" .
mysql_real_escape_string($quote) . "','" .
mysql_real_escape_string($author) . "')";
    $result = mysql_query($query) or die(mysql_error());
    echo ("Saved your Random Quote: " . htmlentities($quote) . " by " .
htmlentities($author) . " into your database");
} else {
    echo ("<p>Please enter a quote and author</p>");
}

Right, lets just take a look at my code above and see what is actually happening here.

if ($_REQUEST['quote'] != "") {

This line basically checks to see if the string ‘quote’ has a value and if so it continues to the next line of coding.

if($_REQUEST['author'] != "") {
        $author = $_REQUEST['author'];
    } else {
        $author = "Not Specified";
    }

This basically checks to see if the string ‘author’ has some value, and if so use that value. If ‘author’ has no value then the code assigned the text ‘Not Specified’ as the value.

$query = "INSERT INTO `random_quote` (`quote`,`author`) values ('" .
mysql_real_escape_string($quote) . "','" . mysql_real_escape_string($author) .
"')";

This code defines the query we did learn about above but notice I have used mysql_real_escape_string(). I have a great reason for this and you should adopt this within all your coding projects. I use mysql_real_escape_string() to stop your programs becoming vunerable to SQL Injection vunerabilities. As a rule from this day forward always escape your users input to be on the safe side.

$result = mysql_query($query) or die(mysql_error());

The result line of code is the actual code that executes your query and saves the input from the form into your database. Again, if this is not possible at that time then an error will be displayed on the screen.

Now, just to make sure you know that the data has been stored into your database we can code a confirmation to let us know that the inputs have been saved to the database successfully.

 echo ("Saved your Random Quote: " . htmlentities($quote) . " by " .
htmlentities($author) . " into your database");

Great, now we have a message that tells us that our data has been saved to the database correctly. So you might not know why I use the code htmlentities() so I am going to let you know the reason. This basically converts symbols like ‘<' into this '<'. This allows your code to not run into Cross Site Scripting (XSS). Again trying to take on board a professional, secure and structured programming technique that saves many headaches further down the line.

Our final part would be this:

} else {
    echo ("<p>Please enter your Quote and Author</p>");
}

If there was no actual quote specified right at the beginning of our code then it would bypass everything we just spoke about and go directly to this code which displays a message on the screen asking the user to input a quote and author.

Well done. You have now basically coded the script ready to take to the next level. But wait... we need a way to get the details from the database and display them on the screen. Now, thats not too hard either so lets move right on to that now.

$query = "SELECT `quote`, `author` FROM `random_quote`";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_numrows($result);
$i = 0;
while ($i < $count) {
$quote = htmlentities(mysql_result($result,$i,"quote"));
$author = htmlentities(mysql_result($result,$i,"author"));
echo ("<blockquote>" . $quote . " ~ <cite>" . $author . "</cite></blockquote>");
$i++;
}

That was not so hard was it. Now lets take a look at what the above code is actually doing here. The first bit of code should be recognised immediately because it is the query that selects the correct columns and the correct table and also now grabs the values for us too:

$query = "SELECT `quote`, `author` FROM `random_quote`";
$result = mysql_query($query) or die(mysql_error());

So now we count how many results we are actually recalling and saving into our array. We do this by using a string called $count. This allows us to count the values in our array and use this value later on.

$count = mysql_numrows($result);

Great, your doing very well so far and I am glad you are keeping up and have not fallen asleep just yet. :) Ok, lets keep going:

$i = 0;

This basically assigns a value to the string 'i'. We need to do this because we are about to loop through our results from our array so this counter is required.

while ($i < $count) {

Ok, here we start our loop using the while statement. This basically checks a value we have set as $count, then we compare this value to our value being stored in the $i string. If $i equals less than $count then it keeps looping until the value becomes equal.

$quote = htmlentities(mysql_result($result,$i,"quote"));
$author = htmlentities(mysql_result($result,$i,"author"));

The above 2 lines basically start with the function mysql_result(), then I specify which result set to use by declaring $result, then I specify which row I would like to pull from the database with the $i string and then specify the correct field/column where my data is stored.

Now a very important thing to remember here is we have set the value of $i to 0. If we were to return the loop now, we would create an infinite loop because our two condition values would never be equal. ($count vs $i) So we need to add a little code so that the value of $i increases by 1 each time the loop returns.

$i++;

Now, all there is left to do is close the connection to the database as we no longer need to keep the connection open.

mysql_close($db_connect);

There we have it. We now have the code that allows us to save our quotes to our database and now recall them and display them on our pages.

Now, all we have to do is create another page called my_random_quotes.php and enter the following code:

<?php
include 'connect.php';
$query="SELECT `quote`, `author` FROM `random_quote` ORDER by rand() LIMIT 1";
$result=mysql_query($query) or die(mysql_error());
$quote = htmlentities(mysql_result($result,$i,"quote"));
$author = htmlentities(mysql_result($result,$i,"author"));
echo("<blockquote>" . $quote . " ~ <cite>" . $author . "</cite></blockquote>");
mysql_close($connection);
?>

Now you should recognise the code above but with a slight change in our $query string.

The only new piece of code we have used is the following:

$query="SELECT `quote`, `author` FROM `quotes` ORDER by rand() LIMIT 1";

This code basically grabs your values from the database table and columns, then uses the function rand() to select at random a row and then LIMIT 1 does exactly what it says. The results are limited to one row only which would only show one quote at a time on your page.

Notice I have used the include() statement so I can call the connect.php file which has all the database credentials stored. Remember to use the include() statement in your save_quote.php file.

There you have it, a great piece of code which will create you a random quote display on your pages. Now if you got a little confused with the coding for the second page called save_quote.php then below is the full code layout of that page. The connect.php and my_random_quotes.php pages are already done for you above.

save_quote.php full code with comments:

<?php // begins php code
include 'connect.php'; // gets your database connect credentials
if ($_REQUEST['quote'] != "") {  // set criteria for 'quote' string
    if($_REQUEST['author'] != "") {  // criteria 'author' anything other than empty?
        $author = $_REQUEST['author'];  // if not empty - use user input
    } else {  // if empty carry on
        $author = "Not Specified";  // empty so fill string with this value
    }
    $quote = $_REQUEST['quote'];  // grabs user input for quote

    $query = "INSERT INTO `random_quote` (`quote`,`author`) values ('" . mysql_real_escape_string($quote) . "','" . mysql_real_escape_string($author) . "')"; // creates query to insert values into database
    $result = mysql_query($query) or die(mysql_error());  // inserts values but on error display error message
    echo ("Saved your Random Quote: " . htmlentities($quote) . " by " . htmlentities($author) . " into your database");  // confirm to user data has been saved
} else {  // if string 'quote' empty, ask user to fill in form correctly
    echo ("<p>Please enter your Quote and Author</p>");  // displays message on 'quote' string empty
}
?> <!-- ends php code -->
<!-- form begins -->
<form action="" method="post"> <!-- creates form and sets method -->
   <label for="quote">Enter Quote:</label> <!-- creats label for input -->
      <input type="text" name="quote" id="quote" maxlength="255" /> <!-- creates input field for Quote -->
   <label for="author">Enter Author:</label> <!-- creats label for input -->
      <input type="text" name="author" id="author" maxlength="50" /> <!-- creates input field for Author -->
         <input type="submit" value="Save Quote" /> <!-- creates submit button with custom text -->
</form> <!-- ends form -->
<!-- form ends -->
<?php // begins php code
$query = "SELECT `quote`, `author` FROM `random_quote`"; // creates query to select from database
$result = mysql_query($query) or die(mysql_error()); // grabs results or display error message
$count = mysql_numrows($result); // counts results placed in temp array
$i=0; // starts counter for loop
while ($i < $count) { // start of our loop that will continue until values $count and $i match
$quote = htmlentities(mysql_result($result,$i,"quote")); // chooses results, row number and column
$author = htmlentities(mysql_result($result,$i,"author")); // choose results, row number and column
echo("<blockquote>" . $quote . " ~ <cite>" . $author . "</cite></blockquote>"); // displays on screen quotes
$i++; // adds one to counter so as to not create infinite loop
}
mysql_close($db_connect); // closes database connection as no longer needed
?> <!-- ends php code -->

2 Responses so far | Have Your Say!

  1. damian  |  December 14th, 2011 at 10:16 pm #

    great article shaun, always wanted to know how to do this and with your extensive detail you have made it very easy for me to understand. thanks

    damian - Gravatar
  2. Shaun Ellerton  |  December 14th, 2011 at 10:21 pm #

    Thanks Damian,

    Great comment and its always nice to hear from one of my readers. If you ever need any assistance with the implementation to your current environment then just give me a shout.

    Best wishes

    Shaun Ellerton - Gravatar

Leave a Feedback

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*