Save a great form in the database

2

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

After the submit of the form, what would be the best way to get these values and then save them to the bank? Best practice, I say use as few rows 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 should be a much easier way to do this (perhaps with a foreach ). ideas, suggestions are all welcome.

    
asked by anonymous 16.10.2015 / 22:04

3 answers

1

In your HTML use the name of the fields equal to the names of the columns 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% re loop%

/*
* $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 field names and values of the fields separated by commas, thus:

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

Now just mount your query.

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

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

if($_POST){ salvar('Tabela_x', $_POST); }
    
16.10.2015 / 22:19
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})");
    
16.10.2015 / 22:24
1

The best practice is not to try to do as few lines as possible, but rather the most readable and easy to maintain, and above all, safe way. Making a clever solution too ( clever ) may harm the code.

You should only get out of the obvious if there is a good reason. You could, for example, loop a loop to mount UPDATE if the form field names match the column names. But this is insecure, so do not. You could create an array with the names of the columns. But it does not help so much. You would either have to clean the data itself from the outside or maybe use an prepared statement , which would make this "simplification" unfeasible.

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

Do not be foolhardy.

    
16.10.2015 / 22:20