Loop to receive form data and write with array [closed]

1

I want to receive the form data with loop, I found an example like this:

foreach($_POST as $nome_campo => $valor) {
   $comando = "$" . $nome_campo . "='" . $valor . "';";
   eval($comando);
} 

But I do not know how I can do to save or edit this data in the database. I do not know if it is possible, because this variable $comando does not show me anything outside foreach .

I want to get: Name, email, password, obs via _POST of the form and add in the bank using a loop, not to do: $nome = $_POST['nome'];
$email = $_POST['email'] ...

and have this data stored in the database.

    
asked by anonymous 15.11.2017 / 00:05

1 answer

1

You can try to create an array before the loop and insert in it the value of the variables of $_POST like this:

$data = array();
foreach($_POST as $nome_campo => $valor) {
   $data[$nome_campo] = $valor;
} 

$sql = "INSERT INTO table_name (column1, column2, column3, ...) values (";

foreach($data as $id => $value) {
    $sql = $sql . " " . $value . " ,";
}

// removo a "," do ultimo loop
$sql = trim(trim($sql),',');
$sql = $sql . ")" ;

But this code can change depending on the rules of your bank, for example if the field can be null could create a if or switch within foreach , it's up to you to specify more to ask or improve this code.

I just created the variable $ data pq so I understood that you would create a variable to receive the values of the variable $_POST but could cut the first part of my code and go straight like this:

$sql = "INSERT INTO table_name (column1, column2, column3, ...) values (";

foreach($_POST as $id => $value) {
    $sql = $sql . " " . $value . " ,";
}

// removo a "," do ultimo loop
$sql = trim(trim($sql),',');
$sql = $sql . ")" ;

Remember that this code is vulnerable to injection, so doing a treatment to avoid this would be good.

    
17.11.2017 / 22:08