SQL Templating





-7
Date Submitted Fri. Feb. 17th, 2006 4:52 AM
Revision 3 of 3
Helper mercutio
Tags mysql
Comments 0 comments
I use this method for keeping my sql templates away from my code.

You can extend upon the idea, as I have done in the past, by placing SQL handing classes between your scripts and the template library.

Things to note here:

The lesser userd heredoc string method. The reason this is used is to keep the SQL clear and well laid out, and not as messy as using quotes.

vsprintf() is a very handy function if you don't want to hard code the number of parameters to interpolate your string with.

The use of sprintf templates offers you additional security. For example, only allowing numbers to be placed where a %d falls. This, of course, shouldn't be the only security on user supplied variables, but comes in extra handy for debugging purposes.

Regarding the TODO in there, it would take a check of the number of % placeholders there are in the template. One caveat is remembering to remove the count of %%'s that appear (the literal percentage).

include 'sql_templates.php';
if (mysql_query(sql_build('fetch_user_by_id', $id))) {
  ...
} else {
  ...
}

if (mysql_query(sql_build('search_all_users', array($group, $email_pattern))) {
  ...
} else {

...

}
 

// A suite of sql statements used throughout the system. Set up as sprintf
//  templates.

// This function runs the template through sprintf and passes any given
//  parameters.
function sql_build($template, $params) {
  global $sql_templates;
  if (isset($sql_templates[$template])) {
    // TODO: verify given parameter count matches params for template.
    if (is_array($params)) {
      $sql = vsprintf($sql_templates[$template], $params);
    } else {
      $sql = sprintf($sql_templates[$template], $params);
    }
    return $sql;
  }
  return false;
}

// Fetch a list of user details
$sql_templates['fetch_user_by_id'] = <<< ENDSQL
select
  id,
  username,
  fullname,
  email
from
  users
where
  id = %d
ENDSQL;
 
.... more templates defined below.... ----------------------------------------------

Tony M

Comments

There are currently no comments for this snippet.

Voting