A little trick to store data into mysql database from a large form

Sometimes we feel boring to write mysql insertion query to store data into database from a large form where are too many input fields (such as about 50 fields). We face problem to handle all the fields, sometimes we miss the field name. Here is a small trick to store data from such a large form.

In this trick, we have to do same naming of table fields and input fields. For example –

[html][/html]

Then the field name of the database will be “first_name”

Then the php code will be:

Suppose, name of the submit button is submit [html][/html]

[php]
safe_entry($_POST); // here obj is the object; safe_entry is a custom function which confirms the input validation of XSS and mysql injection; otherwise you can use $data = safe_entry($_POST); or simply use $data = $_POST;

You may also read:  How to setup a VPS (Ubuntu) for WordPress hosting – A to Z tutorial

$field = $value = array(); //two blank array in which field names and field values will be stored

foreach($data as $key=>$val)

if($key != ‘submit’)

{

array_push($field, $key);

array_push($value, $val);

}

$fields = implode(‘,’, $field);

$values = implode(“‘, ‘”, $value);

$sql = “insert into tablename($fields) values(‘$values’)”;

$query = $obj->insertQuery($sql); //use direct function mysql_query() in stead of custom function and object

?>
[/php]

That’s it! This code will store data from a large form. Thanks.

You may also like...

Leave a Reply

%d bloggers like this: