Loop to receive form data and save with array

Asked

Viewed 779 times

1

I’m wanting to receive the form data with loop, I located an example like this:

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

However I don’t know how I can do to record or edit this data in the database. I do not know if it is possible, because this variable $comando shows me nothing outside the foreach.

I want to take: Name, email, password, Obs via _POST form and add to the database using a loop, so you don’t have to: $nome = $_POST['nome'];
$email = $_POST['email']...

and have these data stored in the database.

  • Why are you wearing the eval?

  • 1

    This code there is not only not safe, using the eval in user data, could be replaced only by function extract: extract($_POST). And which database are you using? Have you been able to connect it? What is the table structure?

  • So I want to receive data with loop and write to the mysql database and get this code there by searching for it in google. I don’t know how to do it, more precise.

1 answer

1


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

$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 database, for example if the field can be null it could create a if or switch within the foreach, it is up to you to specify more to ask or improve this code.

I just created the variable $data pq by which I understood you qria create a variable to receive the values of the variable $_POST but I could cut out 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 . ")" ;

It is worth remembering that this code is vulnerable to Injection, so to do a treatment to avoid this would be good.

  • Thanks for the answer. helped too much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.