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 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端