donglu7286 2010-04-10 13:30
浏览 150
已采纳

循环遍历变量post vars并将它们添加到数据库中

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())");

} 
  • 写回答

2条回答 默认 最新

  • dongqiang5865 2010-04-10 13:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog