Recently, I have noticed that I use the same exact functions over and over again in PHP. I’ve actually set-up a complete function list that I tend to include in all of my projects. Here is an overview of some of them.

Let’s connect

You will need to connect to your database from time to time. It is important to do that in most projects that deal with MySQL, and you’ll probably do it frequently, on every page. Now, you can either delete that “function CustomConnect” and the braces and simply include() this part as a file orrr, just add this to your function list and call it up whenever you need it:

function CustomConnect () {

// MySQL variables
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';

//connect
global $connection;
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
//database select
mysql_select_db($db) or die ("Unable to select database!");
}

I have used this function numerous times before and yes, it works. This is the standard MySQL connection. I set up the variable $connection as global so that variable can be used outside of the function. Why do we need that? You will need that for your mysql_close() function where you will use $connection as your argument variable (inside the parentheses). That will, obviously, close the connection to the mysql database.

Change the username, password, and database according to your own website. Tweak the function as needed. I found it bare-boned and just as I need it for my purposes but you can add default variables, make it more of a “function” if you catch my drift.

Let’s Authenticate

Authentication is essential when creating an admin-side for a website. What does it mean? It means that PHP checks if you are, indeed, the logged in user, and if you have permission to see the site. The PHP is rather simple but effective!

function Authenticate () {
session_start();

if (!$_SESSION['auth'] == 1 || isset($_GET['logout'])) {
    // check if authentication was performed
    // else die with error
	session_destroy();
	header("Location: login.php");
}

}

First, we start a session, this tells the server that we are going to use a session. Next, with an “if” loop, we check if the session variable “auth” is set to one, change this however you need to to indicate that a user is logged in. The $_SESSION[''] variable, if you did not know already, stores variable and information between pages. That means that you don’t need to keep using a “post” form to pass the data along. All of it is there in the session, and can be called up whenever.

As you can see, if either the authentication is not set or the $_GET['logout'] variable is set, you will be redirected to login.php. Basically, this is how you log out! :) You can set up a button or a link to make this work.

This, again, is a bare-boned function. You can add global variables to call on the session variable username or other information.

Let’s Validate

This part is a bit harder.The way I validate is lengthy and redundant, very redundant. Perhaps even wasteful but it works for me and I can sleep soundly because everything is validate correctly. I set up SEVERAL functions to do this:


function isEmailAddress($value) {
        return eregi('^([a-z0-9])+([\.a-z0-9_-])*@([a-z0-9_-])+(\.[a-z0-9_-]+)*\.([a-z]{2,6})$', $value);
    }

function isAlpha($value) {
        return preg_match('/^[a-zA-Z]+$/', $value);
    }
function Alphanum ($value) {
		return preg_match("/^[a-z0-9]+([\\s]{1}[a-z0-9]|[a-z0-9])+$/i", $value);
	}

function name ($var) {
	if (!isAlpha($var)){
	return TRUE;
	}
}

function email ($var) {
	if (!isset($var)){
	return TRUE;
	}
	if (empty($var)){
	return TRUE;
	}
	if (trim($var) == ''){
	return TRUE;
	}
	if (isEmailAddress($var) == 0){
	return TRUE;
	}
}
function message ($var) {
	if (!isset($var)){
	return TRUE;
	}
	if (empty($var)){
	return TRUE;
	}
	if (trim($var) == ''){
	return TRUE;
	}

I told you it was lengthy! All these functions are essential, you may combine some of the “if” statements together with an || or && but I like to keep them separate. As you can see, there are two separate functions above that check for an e-mail address, this is done with pattern recognition. The next function isAlpha does the same but only for alpha characters, Alphanum does the same except that it includes numeric characters. The next three functions (name, email, and message) combine these along with a few “if” statements that check that data has, indeed been submitted via empty($var), trim($var), and other functions already included within PHP. Notice that you will be returned a TRUE value for all of these, meaning that if something is wrong, the result will be true. Use it like this:

if (message($_GET['submittedmessage'])) { echo "Something is wrong";}

And that’s it. If something is wrong, PHP will be echo out “Something is wrong”.

Let’s show some stuff

I like to keep handy one other function that deals with showing the latest entries in a MySQL database. I call it the “ShowComments” function because that is what I originally used it for. You will have to set up this function for each site you’ll use (ie. the rows and stuff like that) but here is what mine generally looks like:

function ShowComments ($var, $where = '') {

$query = "SELECT * FROM database_name $where ORDER BY id DESC";

    // execute query
    $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());

	if (mysql_num_rows($result) > 0) {
				$x = 1;
		while($row = mysql_fetch_row($result) AND $x <= $var) :
			$link = $_SERVER['PHP_SELF']."?id=".$row[0];
       		echo "<p id=\"to\">To: ".stripslashes($row[1])."</p>";
        	echo "<p id=\"message\">" .stripslashes($row[2])."</p>";
			echo "<p id=\"linktime\"><a href=".$link." title=\"permalink".$row[0]."\">permalink</a>  ";
			echo substr($row[3], 0, 10)."</p>";
			echo "</div>
			";
			$x++;
		endwhile;
	}
}

I used this function on one of my latest projects (so ignore the id’s). You can add another parameter into the function to change table names on the go but I usually use this for only one table, such as comments, or a feed. I added the $where part so that I can pick out specific rows rather than just all of them at once. Note that you will have to write the entire “where” statement ie. WHERE id=4 not just id=4, okay? Good.

Here’s an example of how I used it:

<?php
if (!isset($_GET['id'])) {
ShowComments(5);
}
else {
$id = mysql_real_escape_string($_GET['id']);
ShowComments(1, "WHERE id='$id'");
}

Notice how I used it two separate times. Once to show the fave latest comments, the second time to show one specific comment with a specific (escaped) id.

Well, this is it. I hope these functions gave you some insight on how you can speed up your work! :)


Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Reddit
  • Tumblr
  • Twitter
  • email
  • Slashdot
  • StumbleUpon