views:

51

answers:

2

I have been given the task of devising a custom forms manager that has a mysql backend.

The problem I have now encountered after setting up all the front end, is how to process a form that is dynamic.

For E.G

Form one could contain 6 fields all with different name attributes in the input tag. Form two could contain 20 fields all with different name attributes in the input tag.

How would i process the forms without using up oodles of resource.

Final Answer

Based on Accepted answer by Arda Xi

function processForm($form_id) {

    $rows = "";
    $values = "";

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

        $rows = mysql_real_escape_string($key);
        $values = mysql_real_escape_string($value);
        $entry .= "[".$rows . "::".$values."]";

    }
    // clean up the array


    $entry = preg_replace('/^\[|\d+|\:\:\]/', '', $entry);

    $query = mysql_query("INSERT INTO `forms_form_data` (`id`, `form_id`, `entry`, `manager_id`, `status`, `created_at`) VALUES (NULL, '".$form_id."', '".$entry."', '".$_SESSION['manager_id']."', '0', NOW())");

} 
+1  A: 

Literally the only way would be using a loop. If you want to use as little resources as possible, you can concatenate them.

$columns = "";
$values = "";
foreach($_POST as $key => $value) {
    $columns .= "`" . mysql_real_escape_string($key) . "`, ";
    $values .= "`" . mysql_real_escape_string($value) . "`, ";
}
$columns = substr($columns, 0, -2);
$values = substr($values, 0, -2);
$query = "INSERT INTO `table` (".$colums.") VALUES (".$values.")";

This will create one query for all the values in the form.

Arda Xi
looks good, however i forgot to mention the value of each post will only be going into one field in the destination table. how would i incorporate this into what you have said :)
Neil Hickman
So you want the entire form into one field? Like a comma-seperated value?
Arda Xi
essentially, not so much csv as i have my own formatting but all the information submitted via the form will go into table `forms_form_data` row `entry`
Neil Hickman
Could you perhaps show me the code you're using or perhaps a function and what parameters it takes, so I can integrate it into the example above?
Arda Xi
i don't have any functions for processing the form data yet. this is what the question is regards to. i'm not sure what your asking for.
Neil Hickman
Well, you must have some idea in what formatting you want for the entries. Knowing that format is necessary in order to write the code proper.
Arda Xi
I've messed around with your code and got an answer as above.
Neil Hickman
+1  A: 

Why not store the serialized value of $_POST as is? Of course escaping it to make it database safe. Like:

$value=serialize($_POST);
zaf