March 2010
M T W T F S S
« Nov   Apr »
1234567
891011121314
15161718192021
22232425262728
293031  

Processing form data for mySQL insertion

One of the things I frequently come up against, and ended up coding what I consider to be a nice little workaround for, is processing a large form with many elements, and preparing the insert statement to follow.  The following method allows you to continue to add elements onto your form and the database table.

This works for everything except radio buttons or SELECT statements passed as an array, which would need some extra processing.

Hope this helps someone else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#assuming you have a properly formatted form with many elements, passed to this page by $_POST

#an empty array, ready to be populated
$vals = array();

#elements to ignore and not INSERT
$ignore = array('elem1','elem2');

foreach($_POST as $key=>$value){

   /*
   take each passed element and add the key value pair into an array, escaping the value to prevent
   injection attacks, unless the element is in your $ignore array
   */


   if( !in_array($key,$ignore) ){

      $vals[] = "$key='" . @mysql_real_escape_string(stripslashes($value)) . "'";

   }

}

#now compile the sql

$set = implode(', ',$vals);

#and build the SQL

$sql = "INSERT INTO table SET $set";
$result = @mysql_query($sql);

Originally posted at Experts Exchange

Post to Twitter

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>