Simple little random quote generator in PHP/MySQL.

Since I’ve been quite busy otherwise, and have had little to add to the site (codewise), I figured I might give a rather simple, if not overengineered random quote generator.

What this does is look up a prepopulated table of quotes, with personal attributes, and selects, then prints a random one.

First, my mySQL:

CREATE TABLE `quotes` ( `id` int(5) NOT NULL auto_increment, `quote` blob NOT NULL default ‘To err is human. This QuoteDB, however, is in err.’, `ascribe` varchar(200) default NULL, PRIMARY KEY (`id`) )

Then we can just make a silly little subroutine for it like:

– $attribute” : $myString .= ”"”; return($myString); } ?>

Now, connect to your DB as you normally would – for brevity, I’ve created the whole thing as a self containted program, including the data above, as randquote.php:

Note that the above, I populated the existing name for the quote database, the table for the quote, and the person quoted. This is not necessary as I have already set them as defaults within the function – however, again, as a teaching exercise, this might shed a bit more light on how to expand this utility, or use different databases with the same schema.

Notes: I decided upon BLOB rather than varchar() because you can have a really large quote this way, and there should never be a need for an attribute over 200 characters. Again, for brevity, I hardcoded HTML into the random quote generator, this makes it easier to just pass a single string to the executing program.

Note that I have provided no way to edit the existing quotes, or even add existing quotes to the DB. This is left as an exercise to the reader (for now), however, it could be as simple as:

I might later follow up on this, giving a small demonstration of forms in PHP, editing, et al, but that’s beyond the scope of this article.