开发者

looping through variable post vars and adding them to the database

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) {

        $row开发者_开发问答s = 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())");

} 


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.


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

$value=serialize($_POST);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜