Zend - The PHP Company




Databases

Add Code


Database query generator  

Type: code fragment
Added by: gilhildebrandjr
Entered: 04/06/2001
Last modified: 04/12/2008
Rating: **** (9 votes)
Views: 17935
These functions take input from a form and generate a string which can be used in a database query. If you do a lot of database work, this will make your life much easier.


<?

##########################################################################################
#
#     Rapid Form Class
#     Version 1.5
#     Written By Gil Hildebrand Jr (gil@hildebrandconsulting.com)
#     Use is granted under the GNU Public License
#
##########################################################################################
#
# DESCRIPTION:
#    Complimenting the Form to Database Converter, these functions are
#    the missing link between an html form and its database table. They 
#    are designed to accept posted form data and input it directly
#    into a database, without having to type out a list of each form field in 
#    the traditional manner. Name your form fields with "do_" as a prefix so
#    the converter will know what fields you wish to convert.
#
#    Example: for an address field, name it "do_address".
#
##########################################################################
#
# CHANGELOG:
#
# -Version 1.4: The do_insert and do_update functions
#               now have the ability to return an array of
#               required fields which were not filled in. When
#               the "required" attribute in these functions is set,
#               a key/value array is returned with the fields that were
#               required but not filled in.
#
# -Version 1.3: Field merging implemented. You can now
#               merge 2 or more form fields into one.
#               Name them similarly by appending "_merge_x"
#               to the end of each field name, where x is the
#               number of this field. For a phone # field,
#               you could do something like:
#                 <input type="text" size="3" name="do_homephone_merge_1">
#                 <input type="text" size="3" name="do_homephone_merge_2">
#                 <input type="text" size="4" name="do_homephone_merge_3">
#               Thanks to Sean McCann (sean@mudbuginfo.com)
#
#
# -Version 1.2: Added the do_mail function to format
#               a one-value-per-line email with a list of
#               field:value names.
#
#               The do_update function can now process
#               checkboxes which were previously checked
#               but unchecked during the update. It
#               accomplishes this using a hidden form
#               field which acts as an array with
#               the name of each checkbox. 
#               Thanks to Jason Yeast (jasonyeast@hotmail.com)
#
#
# -Version 1.1: Added the do_update function to generate
#               SQL strings for database updates.
#
##############################################################
#
# TODO:
# -Validation for email addresses, phone numbers, etc
# -Researching even more flexibility
#
#####################################################

class formFunctions {

####################
# do_insert function
####################
# Purpose: Produces 2 strings which can be used to make a database insert.
#
# How it works: In your form, name fields with "do_" as a prefix. For example,
#       if the field name in your db is "foobar", then name your form field
#       "do_foobar". Note that you can also make required fields, which will
#       halt the program before any database call if the required field has
#       no value. To use this, name your required field "do_requ_foobar".
#
#       In your program, call the function as follows:
#       list($fields,$values) = do_insert($HTTP_POST_VARS);
#
#       The function will return an array which is broken into the $fields
#       and $values variables. To insert into your db, just do this:
#       mysql_query("Insert into table_name ($fields) VALUES ($values)");
#
# Usage: list($fields,$values) = do_insert($HTTP_POST_VARS);
#        if (!empty($values)) mysql_query("Insert into table_name ($fields) VALUES ($values)");
##################
function do_insert($vars,$required=0) {
  
$this->_mergefields($vars);
  while(list(
$key,$value) = each($vars)) {
    if(
preg_match("/^do_/i",$key)) {
      if(
is_array($value)) {
        
$value implode(",",$value);
        
$columns[] = $key;
        
$values[] = $value;
      }
      else {
        
$columns[] = $key;
        
$values[] = $value;
      }
    }
    if(
preg_match("/requ_/i",$key) && empty($value)) {
      if(
$required == 1$requ[$key] = $value;
      else die(
"The $key field cannot be left empty. Please go back and fill in this field.");
    }
  }

  if(
is_array($requ)) {
    
$requ["required"] = "required";
    return 
$requ;
  }

  
$numcols count($columns);
  
$numvals count($values);

  
$columns preg_replace("/^do_(requ_)?/i"""$columns);

  for(
$i=0;$i<$numcols;$i++) {
    
$columnstring .= $columns[$i];
    if(
$i<$numcols-1$columnstring .= ",";
  }
  for(
$i=0;$i<$numvals;$i++) {
    
$valuestring .= "'$values[$i]'";
    if(
$i<$numvals-1$valuestring .= ",";
  }
  
$return[0] = $columnstring;
  
$return[1] = $valuestring;

  return 
$return;
}


####################
# do_update function
####################
# Purpose: Produces a string which can be used to make a database update.
#
# How it works: In your form, name fields with "do_" as a prefix. For example,
#       if the field name in your db is "foobar", then name your form field
#       "do_foobar". Note that you can also make required fields, which will
#       halt the program before any database call if the required field has
#       no value. To use this, name your required field "do_requ_foobar".
#
#       In your program, call the function as follows:
#       $updatestring = do_update($HTTP_POST_VARS);
#
#       The function will return a variable which can be used as the
#       string for your update query. Example:
#       mysql_query("Update table_name SET $updatestring WHERE foo='bar'");
#
# Usage: $updatestring = do_update($HTTP_POST_VARS);
#        if (!empty($updatestring)) mysql_query("Update table_name SET $updatestring WHERE foo='bar'");
####################
function do_update($vars,$required=0) {
  
$this->_mergefields($vars);
  while(list(
$key,$value) = each($vars)) {
    
$formnames[] = $key;
    
// find value of hidden field checkboxes
    
if($key == "checkboxes") {
      
// more than one checkbox
      
$value explode(",",$value);
      if(
is_array($value)) {
        foreach(
$value as $two_dim_value) {
          
$arrayCheckboxNames[] = $two_dim_value;
        }
      }
      
// only one checkbox -- never really use this, checkboxes is an array
      
else $arrayCheckboxNames $value;
    }
    if(
preg_match("/^do_/i",$key)) {
      if(
is_array($value)) {
        
$value implode(",",$value);
        
$columns[] = $key;
        
$values[] = $value;
      }
      else {
        
$columns[] = $key;
        
$values[] = $value;
      }

   }
    if(
preg_match("/requ_/i",$key) && empty($value)) {
      if(
$required 1$requ[$key] = $value;
      else die(
"The $key field cannot be left empty. Please go back and fill in this field.");
    }
  }

  if(
is_array($requ)) {
    
$requ["required"] = "required";
    return 
$requ;
  }

  
// find checkboxes that are not in the form
  // put 0 value for checkboxes not in the form into the UPDATE statement
  
if(is_array($arrayCheckboxNames)) {
    
$unchecked array_diff($arrayCheckboxNames$formnames);
    foreach(
$unchecked as $value) {
      if(
preg_match("/^do_/i",$value)) {
        
$columns[] = $value;
        
$values[] = "";
      }
    }
  }
  else {
    if(!
in_array($arrayCheckboxNames$formnames)) {
      
$columns[] = $arrayCheckboxNames;
      
$values[] = 0;
    }
  }

  
$numcols count($columns);
  
$numvals count($values);
  
$columns preg_replace("/^do_(requ_)?/i"""$columns);

  for(
$i=0;$i<$numcols;$i++) {
    if(!empty(
$columns[$i])) {
      if(
$i>0$updatestring .= ", ";
      
$updatestring .= $columns[$i] . "='" $values[$i] . "'";
    }
  }
  return 
$updatestring;
}


###################
# do_mail function
###################
# Purpose: Produces a one-per-line string of a form's submitted results
#
# How it works: In your form, name fields with "do_" as a prefix. For example,
#       if the field name in your db is "foobar", then name your form field
#       "do_foobar". Note that you can also make required fields, which will
#       halt the program before any database call if the required field has
#       no value. To use this, name your requ field "do_requ_foobar".
#
#       In your program, call the function as follows:
#       $mailstring = do_mail($HTTP_POST_VARS);
#
#       The function will return an array which is broken into the $fields
#       and $values variables. To insert into your db, just do this:
#       mysql_query("Insert into table_name ($fields) VALUES ($values)");
#
# Usage: $mailstring = do_mail($HTTP_POST_VARS);
#        if(!empty($mailstring)) mail("foo@bar.com","Test Subject",$mailstring);
###################
function do_mail($vars) {
  
$this->_mergefields($vars);
  while(list(
$key,$value) = each($vars)) {
    if(
preg_match("/^do_/i",$key)) {
      if(
is_array($value)) {
        
$value implode(",",$value);
        
$columns[] = $key;
        
$values[] = $value;
      }
      else {
        
$columns[] = $key;
        
$values[] = $value;
      }
    }
    if(
preg_match("/requ_/i",$key) && empty($value)) die("The $key field cannot be left empty. Please go back and fill in this field.");
  }

  
$numcols count($columns);
  
$numvals count($values);

  
$columns preg_replace("/^do_/i"""$columns);
  
$columns preg_replace("/requ_/i"""$columns);

  for(
$i=0;$i<$numcols;$i++) {
    
$mailstring .= $columns[$i] . ": " $values[$i] . "";
    if(
$i<$numcols-1$mailstring .= "n";
  }
  return 
$mailstring;
}

#######################
# _mergefields function
#######################
# Purpose: Merges fields that are in the format field_merge_1, field_merge_2, etc
#
# Usage: Not intended for usage outside of this class
function _mergefields(&$vars){
  
reset($vars);
  while(list(
$key,$value) = each($vars)) {
    if(
preg_match("/^do_.+/i",$key)) {  // if a field is a "do"-field...

      
if(preg_match("/_merge.*_(d)+$/",$key,$captured)) {  // if it ends in a number
        
$key_name preg_replace("/_merge/i","",preg_replace("/_d+$/i","",$key));
        
$keys["$key_name"][(int)$captured[1]] = $value;
      }
      else {
        
$new_array["$key"] = $value;
      }
    }
  }
  if(isset(
$keys)) {
    while(list(
$key,$value) = each($keys)) {
      
$new_array["$key"] = join("-",$keys["$key"]);
    }
  }
  
$vars $new_array;
  
reset($vars);
}

}

?>


Usage Example


For database input:
$updatestring = do_update($HTTP_POST_VARS);
if(!empty($updatestring)) sql_query("Update table_name SET $updatestring WHERE foo='bar'");


Rate This Script





Search



This Category All Categories