My first Code snippet
June 25th, 2008 Posted in Coding | No Comments »Wow, frankly, I’m somewhat proud of myself! This is the first day I’ve had this blog up and this is my second post today! Wow - whoopdi doo, I know. But anyway…let’s get on with this little code snippet. Basically, one of my friends was needing a random Testimonial script, so I decided to step up to the plate and give it a swing. All it really does, is connect to a db, pull the testimonial text from the table, and slap the username in at the end of it. Also - I dropped some CSS in there too, since I just can’t stand to leave something so plain and boring. I’ll also show you the Table I created to pull the data from. Here it is:
<style type="text/css"> #box { color:white; background-color:#42308d; border: 1px lawngreen solid; width:25%; padding:5px; } </style> <? ini_set("error_reporting","E_ALL & ~E_NOTICE"); //Connect to DB $username = 'db_username'; $password = 'user_password'; $db = 'db_name'; $host = 'localhost'; $connect = mysql_connect($host,$username,$password); $seldb = mysql_select_db($db); //Query the db $q1 = mysql_query("SELECT * FROM table"); $rownum = mysql_numrows($q1); //Chooses a random number $num = Rand (1,$rownum); //Based on the random number, gives a quote while($a1 = mysql_fetch_array($q1)) { switch ($num) { case $a1[id]: echo '<div id="box"><font face="Tahoma">" '.$a1[testimonial].'" - '.$a1[username].'</div>'; break; } } ?>
Here’s the SQL:
-- phpMyAdmin SQL Dump -- version 2.11.6 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 25, 2008 at 01:50 AM -- Server version: 5.0.51 -- PHP Version: 5.2.6 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; -- -- Database: `db` -- -- -------------------------------------------------------- -- -- Table structure for table `table` -- CREATE TABLE `table` ( `id` int(4) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `testimonial` text NOT NULL, PRIMARY KEY (`id`), KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
In order to add testimonials, or whatnot you need to know how to run basic INSERT INTO sql statements, if you don’t know how to do that, then your next best bet is using phpMyAdmin, which is how I inserted those in.
A working example can be found here.