PHP Must Have Functions

Whenever I work on a PHP Project, I have certain functions which I always use because they make the coding process so much more easier. Most of this stems from me being really lazy in trying to write more code than neccesary.

The first one is just a simple set of instructions to execute a mysql query and print out an error messages etc. Its a two set function:

function execSql($query, $reason,$d=0) {
  if($d == 0)
    $result = mysql_query($query) or die(SQL_ERROR($reason,$query));
  else
    $result = mysql_query($query) or print($reason);
  return $result;
}

The above function substitutes for me having to type mysql_query($query) or die(SQL_ERROR("This is the reason")); A whole lot of text to type when I'm doing it so many times. This is if I have already written up the SQL_ERROR function. Otherwise, writing this is just a nightmare.

function SQL_ERROR($message,$query) {
  echo "<b><u>Error:</u> $message:</b>";
  echo "<i>".mysql_error()."</i>";
  echo "Original Query: <pre>$query<pre>";
}

This will print out the error in a neat formatted way, something like:
Error: Your customized mysql error message: The error returned by mySQL
Original Query: (SELECT * from table1)

However this above function is best for use when in a development only. Since it will print out your exact SQL query and you may not want that displayed to the user. In the final version I just store the query and the message in the database so I can look at it later.

These two functions are a couple of the functions which make up a core set of functions for my programs. I might post a couple more later. For now this is it, the blog's long enough for me.

Advertisement

One comment

  1. Dennis Mash · ·

    Good info. This will probably work for small to midsized projects but for larger projects there is more than just inserting and throwing out simple error messages.