Loop through post vars variables and add them to the database

I was tasked with developing a custom form manager that has a mysql backend.

The problem I ran into after setting up the whole interface is how to handle the dynamic form.

For EG

The form can contain 6 fields with different name attributes in the input tag. Form 2 can contain 20 fields with different name attributes in the input tag.

How to process forms without using unnecessary resources.

Final answer

Based on the 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


source to share


2 answers


Literally the only way is to use a loop. If you want to use as few resources as possible, you can combine 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 values ​​in the form.

+3


source


Why not keep the serialized $ _POST value as it is? Of course, avoiding it to keep the database safe. How:



$value=serialize($_POST);

      

+1


source







All Articles