1

I want to bulk insert all POST data without having to individually type each name/field. Is the last line that has the mysql INSERT correct? Also I don't have to reprocess mysql_real_escape_string() again for the INSERT correct?

if (is_array($_POST['add']))
   foreach ($_POST['add'] as $key => $value) 
   $_POST['add'][$key] = mysql_real_escape_string(stripslashes($value));

   mysql_query("UPDATE mem SET m_".$key."='".$value."' WHERE m_id=$id");

.... more code

   mysql_query("INSERT INTO meminfo m_".$key." VALUES '".$value."'");
acctman
  • 4,229
  • 30
  • 98
  • 142

2 Answers2

1

This code is injection-prone.

You have to whitelist your keys for protection.
Here is a function to produce SET statement for the mysql queries.

function dbSet($fields, $source = array()) { 
  $set=''; 
  if (!$source) $source = &$_POST; 
  foreach ($fields as $field) { 
    if (isset($source[$field])) { 
      $set.="`$field`='".mysql_real_escape_string($source[$field])."', "; 
    } 
  } 
  return substr($set, 0, -2);  
} 

used like this

$fields = explode(" ","name surname lastname address zip fax phone"); 
$query  = "INSERT INTO $table SET ".dbSet($fields,$_POST['add']); 
$fields = array("foo","bar"); 
$query  = "UPDATE $table SET ".dbSet($fields,$_POST['add'])." where id=".intval($id); 
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-1

You can do something like this:

$fields = $values = $set = '';

foreach ($_POST as $key=>$value) {
  $fields .= '`fld_' . $key . '`,';
  $values .= '"' . mysql_real_escape_string($value) . '",';
  $set .= '`fld_' . $key . '` = "'  . $mysql_real_escape_string($value) .  '",';
}

$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
$set = substr($set, 0, -1);

$sql_insert = 'INSERT INTO `table` (' . $fields . ') VALUES (' . $values . ');';
$sql_update = 'UPDATE `table` SET ' . $set . ' WHERE `fld_id`=' . $id . ';';

This code isn't tested, I just wrote it from the top of my head, there could be some errors.

Slobodan T
  • 22
  • 5