Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Php : Take Input From A Form And Insert It Into A Database

DZone's Guide to

Php : Take Input From A Form And Insert It Into A Database

·
Free Resource
// If you spend a lot of time writing pages that take input from a form and insert it into a database, this function will save you time!
// Please Note: You have to name your form fields the same as their corresponding table column is named in mysql for this to work.
// $table - name of the mysql table you are querying
// $exceptions - fields that will not be inserted into table
//               i.e. 'submit, action, '; (note trailing comma and space!)
// $sql_type - has to be 'insert' or 'update'
// $sql_condition - have to define this if $sql_type = 'update'
//                  i.e. "userID = '".$_POST['userID']."'"


function formToDB($table, $exceptions = '', $sql_type = 'insert', $sql_condition = NULL) {

  // define some vars
  $fields = '';
  $values = '';
 
  // format input fields into sql
  foreach ($_POST as $field => $value) {
   
    if (!strstr($exceptions,$field)) {
   
      $value = mysql_real_escape_string($value);
      if ($sql_type == 'insert') {
       
        $fields .= "$field, ";
        $values .= "'$value', ";
      }
      else {
        $fields .= "$field = '$value', ";
      }
    }
  }
 
  // remove trailing ", " from $fields and $values
  $fields = preg_replace('/, $/', '', $fields);
  $values = preg_replace('/, $/', '', $values);
 
  // create sql statement
  if ($sql_type == 'insert') {
    $sql = "INSERT INTO $table ($fields) VALUES ($values)";
  }
  elseif ($sql_type == 'update') {
    if (!isset($sql_condition)) {
      echo 'ERROR: You must enter a sql condition!';
      exit;
    }
    $sql = "UPDATE $table SET $fields WHERE $sql_condition";
  }
  else {
    echo 'ERROR: Invalid input for argument $sql_type: must be "insert" or "update"';
    exit;
  }
 
  // execute sql
  if (mysql_query($sql)) {
    return true;
  }
  else {
    //echo mysql_error();
    return false;
  }

}
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}