Save a large form to the database

Asked

Viewed 329 times

2

Let’s assume I have a large form, 30 fields containing textareas, radio buttons, checkboxes, select tags, etc..

After the submit from the form, what would be the best way to take these values and then save them in the bank? Best practice, I say use as few lines as possible.

I do it this way

$nome = $_POST['nome '];
$idade = $_POST['idade '];
$cidade = $_POST['cidade '];

and so it goes...

"UPDATE nome_tabela SET var1='$var1', var2='$var2', var3='$var3',...,'var30=$var30' WHERE id='$id'"

There must be a much easier way to do this (perhaps with a foreach). ideas, suggestions are all welcome.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

3 answers

1

In his HTML use the name of the fields equal to the column names of your database, for example:

<form method="post" action="">
<label>Nome:</label>
<input type="text" name="nome" /> <!-- o nome da coluna do banco é nome -->
<label>Idade:</label>
<input type="text" name="idade" /> <!-- o nome da coluna do banco é idade -->

After this create a function to store the data using the repeat loop for

/*
* $tabela é o nome da tabela onde sera salvo os dados
* $dados é o valor passado pelo POST via formulario
*/
public function salvar($tabela, $dados) 
{
foreach($dados as $campo => $valor) {
    $campos[] = $campo; // Criara um array com os nomes dos inputs
    $valores[] = "'$valor'"; // Criara um array com os valores dos inputs
}

$campos = implode(',', $campos); // Junta o array separando os nomes com virgula
$valores = implode(',', $valores); // Junta o array separando os valores com virgula
}

This function will generate the names of the fields and the values of the fields separated by comma;

$campo = "nome, idade" e  $valores = "'joao', '25'";

Now just assemble your query.

$query = "INSERT INTO $tabela($campos) VALUES($valores)";

To call the function make a if in the archive where the form, preferably above the form

if($_POST){ salvar('Tabela_x', $_POST); }

1

The best practice is not to try to do it in as few lines as possible, but in the most legible and easy to maintain, and especially, safe way. Make a solution too smart (Clever) may harm the code.

You should only come out of the obvious if there is a good reason. You could, for example, make a loop to mount the UPDATE if the names of the form fields match the names of the columns. But this is unsafe, then do not. You could create a array , with column names. But it doesn’t help so much. You would have to clean the data itself from outside or maybe use a Prepared statement, what would make this "simplification".

Remembering that some data needs to be formatted before using directly in the database, so this idea of the loop has too many problems to compensate.

Do not be rash, for example allow SQL Injection as it is in your code and the other answers continue to do.

1

$dados = array("nome_da_coluna_nome" => $_POST['nome'],
               "nome_da_coluna_idade" => $_POST['idade'],
               "nome_da_coluna_cidade" => $_POST['cidade']);

$db = new PDO('mysql:host=localhost;dbname=nome_bd', 'usuario_bd', 'senha_bd');
$db->exec("set names utf8"); // opcional para codificação
$tabela = 'nome_da_tabela';

$campos = implode(", ", array_keys($dados));
$valores = "'".implode("','", array_values($dados))."'";
$resultado = $db->query("INSERT INTO `{$tabela}` ({$campos}) VALUES ({$valores})");

Browser other questions tagged

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