PHPStorm Quick Tip: Fix reference class not found errors

Sometimes PHPStorm stops knowing about references or locations of class definitions that were working fine previously. Below is an image (click to enlarge) where PHPStorm tells method not found in class even though class file is included and everything is okay:

phpstorm_class_not_found

This may happen due to a bug in PHPStorm (possibly), unexpected system shutdown, system date time modification or some other reason.

To fix it, you just need to change modified dates of files PHPStorm thinks aren’t there. Once you do that, PHPStorm will reload the changes and will be able to get the reference to those files thereby doing away with such errors. You could simply go to a file and modify it by entering space in its contents or if you have good deals of files, the easiest way would be to touch them. The touch is command line utility that comes with Linux OS. If you are using Windows though, you can download it here. Just run below command to touch all files of the project so PHPStorm knows about class definitions and references of them.

touch -m -c -s -R yourProjectFolder

You can see the options of touch utility by typing touch –help.

 

Free Admin Template

While working on a website or your custom CMS, you need to have an admin template and if you are already provided with one by designer or anyone, that’s good but sometimes you don’t have that option or you want to work on your personal project for which you need the admin template but designer isn’t available or you don’t want to buy an admin template or hire a designer. I often come across this requirement where I need an admin template which should have these features:

  • Easy to customize
  • Slick and nice looking interface
  • Can be modified to as many links as needed, suitable for small to big websites
  • Nice button and form styles
  • Nice looking info messages
  • Can be used as admin for any kind of website

Today I share with you guys an admin template that I created for my personal use. That’s free, you can use it for personal or commercial use.

Screenshots:

This slideshow requires JavaScript.

Download

Which is the Best PHP Framework?

EZMVC – PHP Framework

When working on a PHP project, you have to choose how you are going to develop the site whether you are going to use some framework to develop the site or use custom development.  Both approaches have some dis-advantages, for example if you are going to use some framework then you know framework is not all that easy, if you are going to change something in your site, you have to first search where this change will be made from but if you are going to use the custom approach then it is time-consuming and sort of boring thing.

So what’s the solution?

The solution would be something that comes up with best of the two approaches discussed above. In simple terms, the solution would be to create your own custom framework with some good software patterns like MVC.

I was in similar dilemma as well, so i decided to come up with my own framework which would be simple, easily customizable and fast with ability to add functionality. So the solution I have come up with is named EZMVC, a very easy-to-use framework that can be extended to more power with PHP classes and libraries.

EZMVCEZMVC is an easy-to-use framework implementing the MVC (Model View Controller) design pattern. It helps you create maintainable, flexible and scalable applications. This release of EZMVC framework is very basic, immature, you won’t see all the features present in frameworks like cakephp, codeigniter or symfony in this particular release but I am looking to continue working on this project and come up with an extremely flexible and scaleable framework. Your feedback and suggestions will be greatly appreciated to make this project better and better.

You can download the EZMVC here. The always updated version can be found here:

http://sourceforge.net/projects/ezphp/

.
tweet_this
.

Dealing With SQL Injection

sqlinjectionIf you have no idea about what sql injection is, read this wiki article.

How can we prevent SQL injection attacks?

As with XSS attacks, you must never trust user input. The best way of cleaning user input is using PHP’s built in mysql_real_escape_string() function; this will escape characters such as ‘, ” and others, making them useless in “breaking out” of a quoted string as in the above example. If you’re using a number in your query, then you should use intval() on the inputted number to ensure it is numeric.

I have also made the following function that can be used to discard any characters that can be used to manipulate the SQL queries. So, you can use this functions just as well to validate your SQL queries:

function is_valid($input)
{
    $input = strtolower($input);

    if (str_word_count($input) > 1)
    {
        $loop = true;
        $input = explode(" ",$input);
    }

    $bad_strings = array("'", "--", "select", "union", "insert", "update", "like", "delete", "1=1", "or", "#", "//");

    if ($loop == true)
    {
        foreach($input as $value)
        {
            if (in_array($value, $bad_strings))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
    else
    {
        if (in_array($input, $bad_strings))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

Function Usage

This is how you can use the above function:

if (is_valid($_POST["username"]) == true && is_valid($_POST["password"]) == true)
{
    //login now
}

However, don’t depend on this function alone, you must still use the mysql_real_escape_string() function in your SQL query. You can also modify this function or you can get a new idea to work out of this function.

Handy PHP Tips & Tricks

I have written some handy php tips and tricks right into a php file that puts them to use. You will learn some of the hidden tricks and pitfalls. Of course you would come to this file again and again unless you remember everything it contains. So here is the code with explanation:

$newline = "\n___________________________________________\n\n";
$br = "\n";

////////////////////////////////////////////////////////////
$name = 'Sarfraz';

// variable recognition in single and double quotes
print 'hello $name\n'.$br;
print "hello $name$br";

// reading string varibale as array / extracting text
print $name[3];
print $newline;
////////////////////////////////////////////////////////////

// heredoc: useful way of representing string vars. It can be handy
// in echoing out the html code or related text.
// PHP Comments inside heredocs are not applicable

$url = '/deal.php';
$text = 'Deal More Cards';
$remaining_cards = 5;

print <<< HTML
There are <b>$remaining_cards</b> cards left.

<a href="$url">$text</a>
HTML;
echo $br;

// second example
$a = <<< END
Once upon a time, there was a
END
. ' boy!';
print $a.$br;

// third example

print <<< END
Right now, the time is
END
. strftime('%c') . <<< END
 but tomorrow it will be
END
. strftime('%c',time() + 86400);
print $newline;
////////////////////////////////////////////////////////////

// read chars from backward using negatvie start value
print substr('watch out for that tree',-6);

print $newline;
////////////////////////////////////////////////////////////

$message = <<< TEXT
The function substr_replace is useful when you've got text that's too big to display all at once, and you want to display some of the text with a link to the rest. For example, this displays the first
25 characters of a message with an ellipsis after it as a link to a page that displays more text
TEXT;

printf('<a href="more-text.php?id=%d">%s</a>',
       1, substr_replace($message,' ...',25));
print $newline;
////////////////////////////////////////////////////////////

// counts vowels in a given string using strstr
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    if (strstr('aeiouAEIOU',$string[$i])) {
        $vowels++;
    }
}
print "Number of vowels are: $vowels";
print $newline;
////////////////////////////////////////////////////////////

//To reverse by words, explode the string by word boundary,
// reverse the words, then rejoin:

$s = "Once upon a time there was a turtle.";
$words = explode(' ',$s);
$words = array_reverse($words);
$s = join(' ',$words);
print $s.$br;
print $newline;
////////////////////////////////////////////////////////////

/*
The trim functions can also remove user-specified characters
from strings. Pass the characters you want to remove as a second argument. You can indicate a range of characters with two dots between the first and last characters in the range.
*/
// Remove numerals and space from the beginning of the line
print ltrim('10 means ten',' 0..9').$br;
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
print $newline;
////////////////////////////////////////////////////////////

//Use split( ) or preg_split( ) if you need a POSIX or Perl regular //expression to describe the separator:
// regexp plus means one or more chars
$words = split(' +','This sentence  has  some extra whitespace  in it.');

foreach($words as $value)
{
    print $value . " ";
}
echo $br;
print_r($words);
print $newline;
////////////////////////////////////////////////////////////

/*
Helpfully, is_numeric properly parses decimal numbers, such as 5.1; however, numbers with thousands separators, such as 5,100, cause is_numeric( ) to return false.

To strip the thousands separators from your number before calling is_numeric( ) use str_replace( ):
*/
$number = "5,100";
print is_numeric(str_replace($number, ',', ''));
print $newline;
////////////////////////////////////////////////////////////

// ==========================================
// Variable variables (IMPORTANT)
// ==========================================

/*
You want to construct a variable's name dynamically. For example, you want to use variable names that match the field names from a database query.
*/
$animal = 'turtles';
$turtles = 103;
print $$animal.$br.$br;

/*
The previous example prints 103. Because $animal = 'turtles', $$animal is $turtles,
which equals 103.

Using curly braces, you can construct more complicated expressions that indicate variable names:
*/

$stooges = array('Moe','Larry','Curly');
$stooge_moe = 'Moses Horwitz';
$stooge_larry = 'Louis Feinberg';
$stooge_curly = 'Jerome Horwitz';

foreach ($stooges as $s) {
  print "$s's real name was ${'stooge_'.strtolower($s)}.\n";
}
print $newline;
////////////////////////////////////////////////////////////

// This is how to capture page data before showing it to the user's browser:

$user = "Sarfraz";

ob_start();
var_dump($user);
$dump = ob_get_contents();
ob_end_clean();
print $dump;

print $newline;
////////////////////////////////////////////////////////////

// StrPos Usage Warning

/*
strpos() returns the location of the first substring within a string. If the
substring isn't found, strpos( ) returns false. If it is found, it returns an integer with the position. Therefore, to find a substring position, you might write:
if (strpos($string, $substring)) { found it! }

However, if $substring is found at the exact start of $string, the value returned is 0.
Unfortunately, inside the if, this evaluates to false, so the conditional is not executed.

Here's the correct way to handle the return value of strpos( ):
*/

if (false !== strpos("hello there", "hello")) { print "found"; }

print $newline;
////////////////////////////////////////////////////////////

// open the index.php in main window / frame.
header('Window-target: main');
header('Location: index.php');

////////////////////////////////////////////////////////////

/*
You want to force output to be sent to the browser. For example, before doing a slow database query, you want to give the user a status update.

The flush() function sends all output that PHP has internally buffered to the web server, but the web server may have internal buffering of its own that delays when
the data reaches the browser. Additionally, some browsers don't display data immediately upon receiving it, and some versions of Internet Explorer don't display a page until they've received at least 256 bytes. To force IE to display content, print blank
spaces at the beginning of the page:
*/

print str_repeat(' ',300);
print 'Finding identical snowflakes...';
flush();
$sth = $dbh->query('SELECT shape,COUNT(*) AS c FROM snowflakes');
////////////////////////////////////////////////////////////
/*
You want to start generating output before you're finished sending headers or cookies.

Call ob_start at the top of your page and ob_end_flush( ) at the bottom. You can
then intermix commands that generate output and commands that send headers.
The output won't be sent until ob_end_flush( ) is called:
*/

/*
<?php ob_start(); ?>
I haven't decided if I want to send a cookie yet.
<?php setcookie('heron','great blue'); ?>
Yes, sending that cookie was the right decision.
<?php ob_end_flush(); ?>
*/

/*
You can pass ob_start( ) the name of a callback function to process the output buffer with that function. This is useful for postprocessing all the content in a page, such as hiding email addresses from address-harvesting robots:

<?php
function mangle_email($s) {
    return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                        '<$1@...>',
                        $s);
}

ob_start('mangle_email');
?>

I would not like spam sent to ronald@example.com!

<?php ob_end_flush(); ?>

The mangle_email( ) function transforms the output to:
I would not like spam sent to <ronald@...>!
*/
////////////////////////////////////////////////////////////
/*
You want to process a variable with a period in its name, but when a form is submitted, you
can't find the variable.

Replace the period in the variable's name with an underscore. For example, if you have a form
input element named foo.bar, you access it inside PHP as the variable $_REQUEST['foo_bar'].

Because PHP uses the period as a string concatenation operator, a form variable called
animal.height is automatically converted to animal_height, which avoids creating an
ambiguity for the parser. While $_REQUEST['animal.height'] lacks these ambiguities, for
legacy and consistency reasons, this happens regardless of your register_globals
settings.
*/

////////////////////////////////////////////////////////////

/*
You can put a username and password in the URL if you need to retrieve a protected page. In
this example, the username is david, and the password is hax0r. Here's how to do it with
fopen( ):

$fh = fopen('http://david:hax0r@www.example.com/secrets.html','r')
    or die($php_errormsg);
while (! feof($fh)) {
    $page .= fread($fh,1048576);
}
fclose($fh);
*/
////////////////////////////////////////////////////////////

// Build query string from an array

$query = http_build_query($array);

////////////////////////////////////////////////////////////

QuickDB – The MySQL Wrapper

quickdbWhen working on different projects, you have to use time-consuming mysql commands every now and then. Same was the case with me and i had really got sick of all those commands, so i decided to create my own mysql wrapper with ability to perform the similar tasks far more quickly and easily than their mysql counterparts. I have used it in many projects i have developed and it has saved me about 50% of the time as compared to using mysql default functions.

You can download the file whole class with example here.

.
tweet_this
.

So here is the code for the sample file, name it quickdb_example.php

	// Online Class Location:
	// http://www.phpclasses.org/browse/package/5318.html

	/*

	In order to use the example here, you need to create a table,
	just execute the following SQL lines using your MySQL client:
	-------------------------------------------------------------

	################################
	CREATE TABLE `quickdbtest` (
	  `catid` int(11) NOT NULL auto_increment,
	  `catname` varchar(255) default NULL,
	  PRIMARY KEY  (`catid`)
	);
	insert  into `quickdbtest`(`catid`,`catname`) values (1,'Big'),(2,'Small'),(3,'Average'),(4,'Light'),(5,'Huge');
	################################

	*/

	// This file uses most of the functions of QuickDB MySQL wrapper.
	// It is very easy to use these funtions (methods), see below examples.
	// Once you know how to use this, i bet you are gonna use it in future as well :)

	require_once "quickdb.class.php";
	// Argumentd are: host, user, password, database, persistent connection, show errors on screen
	$db = new QuickDB("localhost", "root", "", "test", false, true);

	## execute Method/Function
	// it can run any query whether select, insert, update or delete like mysql_query function

	// returns:
	// 1) resource identifier for "Select query" that can later be used with mysql_fetch_array or mysql_fetch_object
	// 2) number of rows affected for "insert, update or delete" queries

																											// Usage Of:
																											// --------------------------

	$result = $db->execute("select * from quickdbtest order by catname");									// $db->execute
	// Or
	// 		$result = $db->select("quickdbtest");															// $db->select

	while ($row = mysql_fetch_array($result))
	{
		print $row["catname"] . "
";
	}

	print "
Number of rows selected from previous query : " . $db->count_select();						// $db->count_select()

	$affected = $db->execute("insert into quickdbtest set catname = 'New Category'");
	// Or
	//		$affected = $db->insert("quickdbtest", "catname = 'New Category'");								// $db->insert

	print "
Number of rows affected are: $affected";
	// Or
	print "
Number of rows affected using class method: " . $db->count_affected();						// $db->count_affected()
	$db->success_msg("Record was added successfully !!");

	$affected = $db->update("quickdbtest", "catname = 'New Category 2'", "catname = 'New Category'");		// $db->update
	print "
Number of rows affected are: $affected";

	$db->delete("quickdbtest", "catid = " . $db->last_insert_id());											// $db->last_insert_id(), $db->delete
	print "
Number of rows affected using class method: " . $db->count_affected();

	print "
Total records in table are: " . $db->count_all("quickdbtest");								// $db->count_all

	print "
Counting records using 'count_rows' : " . $db->count_rows("select * from quickdbtest");	// $db->count_rows

	// $db->insert_update will update if row exists, or insert data if it doesn't with catid=5
	$affected = $db->insert_update("quickdbtest", "catname='Test Category'", "catid=5");					// $db->insert_update
	print "
Number of rows affected are: $affected
";

	$result = $db->select_limited("quickdbtest", 4, 1);														// $db->select_limited

	while ($row = mysql_fetch_array($result))
	{
		print $row["catname"] . "
";
	}

	if ($db->has_rows("quickdbtest"))																		// $db->has_rows
	{
		print "This table is not empty, it has rows in it !!";
	}
	else
	{
		print "Oops, the table is empty !!!";
	}

	if ($db->row_exists("select * from quickdbtest where catid = 5"))										// $db->row_exists
	{
		print "
Yes, row exists";
	}
	else
	{
		print "
No, row does not exist";
	}

	// fetch a single row from db
	$row = $db->fetch_row("select * from quickdbtest where catid = 1");										// $db->fetch_row
	print "
The fetched values are: " . $row->catid . " " . $row->catname ;

	// fetch a single row from db
	$catname = $db->fetch_value("quickdbtest", "catname", "catid = 3");										// $db->fetch_value
	print "
The fetched value is: " . $catname;

	print "
 The date today is: " . $db->get_date();													// $db->get_date()
	print "
 The current time is: " . $db->get_time();													// $db->get_time()

	// $db->last_query() gives the last run query, may be useful for debugging queries
	print "
 The last run query was: <strong>" . $db->last_query()  . "</strong>

";

	// using very useful $db->load_data()
	$db->select("quickdbtest");																				// $db->select
	$data = $db->load_array();																				// $db->load_array()
	print_r($data);
	/////////////////////////

	// using another very useful function that convert db table to a html table
	$db->get_html("select * from quickdbtest order by catname" , true, 'width = 50%, align="center"');		// $db->get_html

	print "
<strong>Database Tables</strong>
";
	$db->list_tables();																						// $db->list_tables()

	print "
<strong>Table Information</strong>
";
	$db->table_info("quickdbtest");																			// $db->table_info

	$db->success_msg("Wow, this is cool class !!");															// $db->success_msg

	// just a wrong table to get that error
	$db->count_rows("select * from NO_TABLE");
	$db->display_errors();																					// $db->display_errros()

	$db->failure_msg("Oops, i must have received the error !!");											// $db->failure_msg

	$db->alert_msg("This is general alert message !!");														// $db->alert_msg

	print "

" . $db->success_msg("<STRONG>REQUEST:</STRONG> IF YOU LIKE THIS THEN PLEASE GO AHEAD AND <a href='http://www.phpclasses.org/browse/package/5318.html'>RATE</a> THIS AT PHPCLASSES.ORG, THANKS :)") . "

";

and here is the code for the class itself, quickdb.class.php

	#########################################################
	#			QuickDB->MySQL Wrapper Class				#
	#-------------------------------------------------------#
	#	Author: SARFRAZ AHMED CHANDIO						#
	#			Web Developer								#
	#			Brains Technology							#
	#			http://www.brainstech.com					#
	#			https://sarfraznawaz.wordpress.com			#
	#														#
	#	Date Created: 12 April 2009							#
	#########################################################

	#-------------------------------------------------------#
	# 	+++ Future Additions +++							#
	#-------------------------------------------------------#
	#	Paging												#
	#	Multi-Language Support								#
	#-------------------------------------------------------#

	class QuickDB
	{
		private $con 			= null;		// for db connection
		private $result 		= null;		// for mysql result resource id
		private $row 			= null;		// for fetched row
		private $rows 			= null;		// for number of rows fetched
		private $affected 		= null;		// for number of rows affected
		private $insert_id 		= null;		// for last inserted id
		private $query 			= null;		// for the last run query
		private $show_errors 	= null;		// for knowing whether to display errors
		private $emsg 			= null;		// for mysql error description
		private $eno 			= null;		// for mysql error number

		// Intialize the class with connection to db
		public function __construct($host, $user, $password, $db, $persistent = false, $show_errors = false)
		{
			if ($show_errors == true)
			{
				$this->show_errors = true;
			}

			if ($persistent == true)
			{
				$this->con = @mysql_pconnect($host, $user, $password);
			}
			else
			{
				$this->con = @mysql_connect($host, $user, $password);
			}

			if ($this->con)
			{
				$result = mysql_select_db($db, $this->con) or die("Could Not Select The Database !!");
				return $result;
			}
			else
			{
				die("Could Not Establish The Connection !!");
			}
		}

		// Close the connection to database
		public function __destruct()
		{
			$this->close();
		}

		// Close the connection to database
		public function close()
		{
			$result = @mysql_close($this->con);
			return $result;
		}

		// stores mysql errors
		private function setError($msg, $no)
		{
			$this->emsg = $msg;
			$this->eno = $no;

			if ($this->show_errors == true)
			{
				print '
<div style="background:#f6f6f6; padding:5px; font-size:13px; font-family:verdana; border:1px solid #cccccc;">
						<span style="color:#ff0000;">MySQL Error Number</span> : ' . $no . '
						<span style="color:#ff0000;">MySQL Error Message</span> : ' . $msg . '</div>
';
			}
		}

		#################################################
		#				General Functions				#
		#################################################

		// Runs the SQL query (general execute query function)
		public function execute($command)
		{
			# Params:
			# 		$command = query command

			if (!$command)
			{
				exit("No Query Command Specified !!");
			}

			$this->query = $command;

			// For Operational query
			if 	(
				(stripos($command, "insert ") !== false) ||
				(stripos($command, "update ") !== false) ||
				(stripos($command, "delete ") !== false) ||
				(stripos($command, "replace ") !== false)
				)
			{
				$this->result = mysql_query($command) or $this->setError(mysql_error(), mysql_errno());

				if (stripos($command, "insert ") !== false)
				{
					if ($this->result)
					{
						$this->insert_id = intval(mysql_insert_id());
					}
				}

				if ($this->result)
				{
					$this->affected = intval(mysql_affected_rows());
					// return the number of rows affected
					return $this->affected;
				}
			}
			else
			{
				// For Selection query
				$this->result = mysql_query($command) or $this->setError(mysql_error(), mysql_errno());
				if ($this->result)
				{
					$this->rows = intval(mysql_num_rows($this->result));
					// return the query resource for later processing
					return $this->result;
				}
			}
		}

		// Gets records from table
		public function select($table, $rows = "*", $condition = null, $order = null)
		{
			# Params:
			# 		$table = the name of the table
			#		$rows = rows to be selected
			# 		$condition = example: where id = 99
			#		$order = ordering field name

			if (!$table)
			{
				exit("No Table Specified !!");
			}

			$sql = "select $rows from $table";

			if($condition)
			{
				$sql .= ' where ' . $condition;
			}
			else if($order)
			{
				$sql .= ' order by ' . $order;
			}

			$this->query = $sql;
			$this->result = mysql_query($sql) or $this->setError(mysql_error(), mysql_errno());

			if ($this->result)
			{
				$this->rows = intval(mysql_num_rows($this->result));
				// return the query resource for later processing
				return $this->result;
			}
		}

		// Inserts records
		public function insert($table, $data)
		{
			# Params:
			# 		$table = the name of the table
			# 		$data = field/value pairs to be inserted

			if ($table)
			{
				if ($data)
				{
					$this->result = mysql_query("insert into $table set $data") or $this->setError(mysql_error(), mysql_errno());
					$this->query = "insert into $table set $data";

					if ($this->result)
					{
						$this->affected = intval(mysql_affected_rows());
						$this->insert_id = intval(mysql_insert_id());
						// return the number of rows affected
						return $this->affected;
					}
				}
				else
				{
					print "No Data Specified !!";
				}
			}
			else
			{
				print "No Table Specified !!";
			}
		}

		// Updates records
		public function update($table, $data, $condition)
		{
			# Params:
			# 		$table = the name of the table
			# 		$data = field/value pairs to be updated
			# 		$condition = example: where id = 99

			if ($table)
			{
				if ($data)
				{
					if ($condition)
					{
						$this->result = mysql_query("update $table set $data where $condition") or $this->setError(mysql_error(), mysql_errno());
						$this->query = "update $table set $data where $condition";

						if ($this->result)
						{
							$this->affected = intval(mysql_affected_rows());
							// return the number of rows affected
							return $this->affected;
						}
					}
					else
					{
						print "No Condition Specified !!";
					}
				}
				else
				{
					print "No Data Specified !!";
				}
			}
			else
			{
				print "No Table Specified !!";
			}
		}

		// Deletes records
		public function delete($table, $condition)
		{
			# Params:
			# 		$table = the name of the table
			# 		$condition = example: where id = 99

			if ($table)
			{
				if ($condition)
				{
					$this->result = mysql_query("delete from $table where $condition") or $this->setError(mysql_error(), mysql_errno());
					$this->query = "delete from $table where $condition";

					if ($this->result)
					{
						$this->affected = intval(mysql_affected_rows());
						// return the number of rows affected
						return $this->affected;
					}
				}
				else
				{
					print "No Condition Specified !!";
				}
			}
			else
			{
				print "No Table Specified !!";
			}
		}

		// returns table data in array
		public function load_array()
		{
			$arr = array();

			while ($row = mysql_fetch_object($this->result))
			{
				$arr[] = $row;
			}

			return $arr;
		}

		// print a complete html table from the specified db table
		public function get_html($command, $display_field_headers = true, $table_attribs = 'border="0" cellpadding="5" cellspacing="0" style="padding-bottom:5px; border:1px solid #cccccc; font-size:13px; font-family:verdana;"')
		{
			if (!$command)
			{
				exit("No Query Command Specified !!");
			}

			$this->query = $command;
			$this->result = mysql_query($command) or $this->setError(mysql_error(), mysql_errno());

			if ($this->result)
			{
				$this->rows = intval(mysql_num_rows($this->result));

				$num_fields = mysql_num_fields($this->result);

				print '
<div>
<table ' . $table_attribs . '>'
						. "\n" . '
<tr>';

				if ($display_field_headers == true)
				{
					// printing table headers
					for($i = 0; $i < $num_fields; $i++)
					{
						$field = mysql_fetch_field($this->result);
						print "
<td bgcolor='#f6f6f6' style=' border:1px solid #cccccc; padding:5px;'><strong style='color:#666666;'>" . ucwords($field->name) . "</strong></td>
\n";
					}
					print "</tr>
\n";
				}

				// printing table rows
				while($row = mysql_fetch_row($this->result))
				{
					print "
<tr>";

					foreach($row as $td)
					{
						print "
<td bgcolor='#f6f6f6'>$td</td>
\n";
					}

					print "</tr>
\n";
				}
				print "</table>
</div>
";
			}
		}

		public function last_insert_id()
		{
			if ($this->insert_id)
			{
				return $this->insert_id;
			}
		}

		// Counts all records from a table
		public function count_all($table)
		{
			if (!$table)
			{
				exit("No Table Specified !!");
			}

			$this->result = mysql_query("select count(*) as total from $table") or $this->setError(mysql_error(), mysql_errno());
			$this->query = "select count(*) as total from $table";

			if ($this->result)
			{
				$this->row = mysql_fetch_array($this->result);
				return intval($this->row["total"]);
			}
		}

		// Counts records based on specified criteria
		public function count_rows($command)
		{
			# Params:
			# 		$command = query command

			if (!$command)
			{
				exit("No Query Command Specified !!");
			}

			$this->query = $command;
			$this->result = mysql_query($command) or $this->setError(mysql_error(), mysql_errno());

			if ($this->result)
			{
				return intval(mysql_num_rows($this->result));
			}
		}

		// Updates a row if it exists or adds if it doesn't already exist.
		public function insert_update($table, $data, $condition)
		{
			# Params:
			# 		$table = the name of the table
			# 		$data = field/value pairs to be added/updated
			# 		$condition = example: where id = 99

			if ($table)
			{
				if ($data)
				{
					if ($condition)
					{
						if ($this->row_exists("select * from $table where $condition"))
						{
							$this->result = mysql_query("update $table set $data where $condition") or $this->setError(mysql_error(), mysql_errno());
							$this->query = "update $table set $data where $condition";

							if ($this->result)
							{
								$this->affected = intval(mysql_affected_rows());
								// return the number of rows affected
								return $this->affected;
							}
						}
						else
						{
							$this->result = mysql_query("insert into $table set $data") or $this->setError(mysql_error(), mysql_errno());
							$this->query = "insert into $table set $data";

							if ($this->result)
							{
								$this->insert_id = intval(mysql_insert_id());
								$this->affected = intval(mysql_affected_rows());
								// return the number of rows affected
								return $this->affected;
							}
						}
					}
					else
					{
						print "No Condition Specified !!";
					}
				}
				else
				{
					print "No Data Specified !!";
				}
			}
			else
			{
				print "No Table Specified !!";
			}
		}

		// Runs the sql query with claus "limit x, x"
		public function select_limited($table, $start, $return_count, $condition = null, $order = null)
		{
			# Params:
			# 		$start = starting row for limit clause
			# 		$return_count = number of records to fetch
			# 		$condition = example: where id = 99
			# 		$order = ordering field name

			if ($table && $start >= 0 && $return_count)
			{
				if ($condition)
				{
					if ($order)
					{
						$this->result = mysql_query("select * from $table where $condition order by $order limit $start, $return_count") or $this->setError(mysql_error(), mysql_errno());
						$this->query = "select * from $table where $condition order by $order limit $start, $return_count";
					}
					else
					{
						$this->result = mysql_query("select * from $table where $condition limit $start, $return_count") or $this->setError(mysql_error(), mysql_errno());
						$this->query = "select * from $table where $condition limit $start, $return_count";
					}
				}
				else
				{
					if ($order)
					{
						$this->result = mysql_query("select * from $table order by $order limit $start, $return_count") or $this->setError(mysql_error(), mysql_errno());
						$this->query = "select * from $table order by $order limit $start, $return_count";
					}
					else
					{
						$this->result = mysql_query("select * from $table limit $start, $return_count") or $this->setError(mysql_error(), mysql_errno());
						$this->query = "select * from $table limit $start, $return_count";
					}
				}

				if ($this->result)
				{
					$this->rows = intval(mysql_num_rows($this->result));
					// return the query resource for later processing
					return $this->result;
				}
			}
			else
			{
				print "Parameter Missing !!";
			}
		}

		#################################################
		#				Utility Functions				#
		#################################################

		// Counts rows from last Select query
		public function count_select()
		{
			if ($this->rows)
			{
				return $this->rows;
			}
		}

		// Gets the number of affected rows after Operational query has executed
		public function count_affected()
		{
			if ($this->affected)
			{
				return $this->affected;
			}
		}

		// Checks whether a table has records
		public function has_rows($table)
		{
			$rows = $this->count_all($table);

			if ($rows)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		// Checks whether or not a row exists with specified criteria
		public function row_exists($command)
		{
			# Params:
			# 		$command = query command

			if (!$command)
			{
				exit("No Query Command Specified !!");
			}

			$this->query = $command;
			$this->result = mysql_query($command) or $this->setError(mysql_error(), mysql_errno());

			if ($this->result)
			{
				if (mysql_num_rows($this->result))
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}

		// Returns single fetched row
		public function fetch_row($command)
		{

			if (!$command)
			{
				exit("No Query Command Specified !!");
			}

			$this->query = $command;
			$this->result = mysql_query($command) or $this->setError(mysql_error(), mysql_errno());

			if ($this->result)
			{
				$this->rows = intval(mysql_num_rows($this->result));
				$this->row = mysql_fetch_object($this->result);
				return $this->row;
			}
		}

		// Returns single field value
		public function fetch_value($table, $field, $condition = null)
		{

			if (!$table || !$field)
			{
				exit("Arguments Missing !!");
			}

			$query = "select $field from $table";

			if ($condition != null)
			{
				$query = "select $field from $table where $condition";
			}

			$this->query = $query;
			$this->result = mysql_query($query) or $this->setError(mysql_error(), mysql_errno());

			if ($this->result)
			{
				$this->rows = intval(mysql_num_rows($this->result));
				$this->row = mysql_fetch_object($this->result);
				return $this->row->$field;
			}
		}

		// Returns the last run query, useful for debugging queries
		public function last_query()
		{
			if ($this->query)
			{
				return $this->alert_msg($this->query);
			}
		}

		// Gets today's date
		public function get_date($format = null)
		{
			# Params:
			#		$format = date format like Y-m-d

			if ($format)
			{
				$today = date($format);
			}
			else
			{
				$today = date("Y-m-d");
			}

			return $today;
		}

		// Gets currents time
		public function get_time($format = null)
		{
			# Params:
			#		$format = date format like H:m:s

			if ($format)
			{
				$time = date($format);
			}
			else
			{
				$time = date("H:m:s");
			}

			return $time;
		}

		// Adds slash to the string irrespective of the setting of getmagicquotesgpc
		public function smartslashes($value)
		{
			if (get_magic_quotes_gpc())
			{
				$value = stripslashes($value);
			}

			if (!is_numeric($value))
			{
				$value = mysql_real_escape_string($value);
			}

			return $value;
		}

		// This function can be used to discard any characters that can be used to manipulate the SQL queries or SQL injection

		/* EXAMPLE USE:

			if (is_valid($_REQUEST["username"]) === true && is_valid($_REQUEST["pass"]) === true)
			{
				//login now
			}
		*/

		public function is_valid($input)
		{
			$input = strtolower($input);

			if (str_word_count($input) > 1)
			{
				$loop = "true";
				$input = explode(" ",$input);
			}

			$bad_strings = array("'","--","select","union","insert","update","like","delete","1=1","or");

			if ($loop)
			{
				foreach($input as $value)
				{
					if (in_array($value, $bad_strings))
					{
					  return false;
					}
					else
					{
					  return true;
					}
				}
			}
			else
			{
				if (in_array($input, $bad_strings))
				{
				  return false;
				}
				else
				{
				  return true;
				}
			}
		}

		// lists tables of database
		public function list_tables()
		{
			$this->result = mysql_query("show tables");
			$this->query = "show tables";

			if ($this->result)
			{
				$tables = array();
				while($row = mysql_fetch_array($this->result))
				{
					$tables[] = $row[0];
				}

				foreach ($tables as $table)
				{
					print $table . "
";
				}
			}
		}

		// provides info about given table
		public function table_info($table)
		{
			if ($table)
			{
				$this->result = mysql_query("select * from $table");
				$this->query = "select * from $table";

				$fields = mysql_num_fields($this->result);
				$rows   = mysql_num_rows($this->result);
				$table = mysql_field_table($this->result, 0);

				print "	The '<strong>" . $table . "</strong>' table has <strong>" . $fields . "</strong> fields and <strong>" . $rows . "</strong>
						record(s) with following fields.\n
<ul>";

				for ($i=0; $i < $fields; $i++)
				{
					$type  = mysql_field_type($this->result, $i);
					$name  = mysql_field_name($this->result, $i);
					$len   = mysql_field_len($this->result, $i);
					$flags = mysql_field_flags($this->result, $i);

					print "<strong>
	<li>" . $type . " " . $name . " " . $len . " " . $flags . "</strong></li>
\n";
				}
				print "</ul>
";

			}
			else
			{
				print "The table not specified !!";
			}
		}

		// displays any mysql errors generated
		public function display_errors()
		{
			if ($this->show_errors == false)
			{
				if ($this->emsg)
				{
					print '
<div style="background:#f6f6f6; padding:5px; font-size:13px; font-family:verdana; border:1px solid #cccccc;">
							<span style="color:#ff0000;">MySQL Error Number</span> : ' . $this->eno . '
							<span style="color:#ff0000;">MySQL Error Message</span> : ' . $this->emsg . '</div>
';
				}
				else
				{
					print '
<div style="background:#f6f6f6; padding:5px; font-size:13px; font-family:verdana; border:1px solid #cccccc;">
							<strong>No Erros Found !!</strong></div>
';
				}
			}
		}

		// to display success message
		public function success_msg($msg)
		{
			print '
<div align="center" style="background:#EEFDD7; padding:5px; font-size:13px; font-family:tahoma, verdana; border:1px solid #8DD607; margin:5px 0px 5px 0px;">
					<strong>' . $msg . '
					</strong></div>
';
		}

		// to display failure message
		public function failure_msg($msg)
		{
			print '
<div align="center" style="background:#FFF2F2; padding:5px; font-size:13px; font-family:tahoma, verdana; border:1px solid #FF8080; margin:5px 0px 5px 0px;">
					<strong>' . $msg . '
					</strong></div>
';
		}

		// to display general alert message
		public function alert_msg($msg)
		{
			print '
<div align="center" style="background:#FFFFCC; padding:5px; font-size:13px; font-family:tahoma, verdana; border:1px solid #CCCC33; margin:5px 0px 5px 0px;">
					<strong>' . $msg . '
					</strong></div>
';
		}

	////////////////////////////////////////////////////////
	}

Enjoy and reply with your feedbacks :)