Community Documentation

Simple function for MYSQL INSERT and UPDATE in Drupal custom modules

Last updated April 10, 2012. Created by anbuindia on March 15, 2010.
Edited by shamio. Log in to edit this page.

Use this following function to insert and update, this is to avoid insert update statements in every custom module

/*
* $tablename to get all fields from this tablename
*/
function get_fields_from_table($tablename){
  $qry = db_query("SHOW COLUMNS FROM $tablename");
  while ($row = db_fetch_object($qry)) {
    $fields[] = $row->Field;
  }
  return $fields;
}
/*
* $values It should be a array, it contains key as field name
* $tablename pass the table where you want to insert
*/
function save_to_table($values,$tablename){
  if(count($values)){
    $transaction_fields = get_fields_from_table($tablename);
    foreach ($transaction_fields as $key) {
      if (isset($values[$key])) {
        $k[] = db_escape_string($key);
        $v[] = $values[$key];
        $s[] = "'%s'";
      }
    }
    if(count($k)){
      db_query('INSERT INTO {'.$tablename.'} ('. implode(', ', $k) .') VALUES('. implode(', ', $s) .')', $v);
    }
  }
}
/*
* $values It should be a array, it contains key as field name
* $tablename pass the table where you want to insert
* $where_field where condition field name
* $idval value of thet filed
*/
function update_to_table($values,$tablename,$where_field,$idval){
  if(count($values)){
    $transaction_fields = get_fields_from_table($tablename);
    foreach ($transaction_fields as $key) {
      if (isset($values[$key]) && !empty($values[$key])) {
        $q[] = db_escape_string($key) ." = '%s'";
        $v[] = $values[$key];
      }
    }
    if (is_array($q) && is_array($v)) {
      db_query('UPDATE {'.$tablename.'} SET '. implode(', ', $q) ." WHERE $where_field = '$idval'", $v);
    }
  }
}
//Example
/*
$values['field1']='pass the value of field';
$values['field2']='pass the value of field';
$values['field3']='pass the value of field';
save_to_table($values,'tablename');*/

About this page

Drupal version
Drupal 5.x, Drupal 6.x
Audience
Programmers

Reference

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.