1
I have a form with personal data of the client and I wanted to send this data to a class that has a method that saves the data in the database, but the form is very large and I wanted to send an array or the POST itself, but I didn’t want to keep breaking it into variables, send the entire array to the bank.
$res = $cliente->cadastrar_cliente($_POST['name'],$_POST['cpf_cnpj'],
$_POST['name_fan'],$_POST['zip_code'],
$_POST['city'],$_POST['state'],$_POST['street'],
$_POST['complement'],$_POST['district'],$_POST['district'],
$_POST['email'],$_POST['password'],$_POST['telefone'],$_POST['celular'])
I’m sending this way, this is in the view, I wanted to send something less "ugly" not to leave the view messy.
function cadastrar_cliente(
$nome_responsavel, $cpf_cnpj = null, $nome_fantasia, $cep,
$cidade,$uf,$rua, $complemento,$bairro,$numero,$email, $senha, $telefone = null, $celular)
{
$pdo = $this->conn->open_connect("db_forpaper");
$sql = "INSERT INTO tbl_cliente (nome_responsavel,cpf_cnpj,nome_fantasia,cep,
cidade,uf,rua,complemento,bairro,numero,email,senha,telefone,celular)
VALUES ('$nome_responsavel', '$cpf_cnpj', '$nome_fantasia', '$cep', '$cidade',
'$uf','$rua','$complemento','$bairro','$numero','$email','$senha','$telefone','$celular')";
$insert = $pdo->prepare($sql)->execute();
if($insert){
$res = "ok";
}else{
$res = "erro";
}
return $res;
}
So I take my class with the method of registration.
function cadastrar_cliente($_POST)
{
$pdo = $this->conn->open_connect("db_forpaper");
$sql = "INSERT INTO tbl_cliente (nome_responsavel,cpf_cnpj,nome_fantasia,cep,
cidade,uf,rua,complemento,bairro,numero,email,senha,telefone,celular)
VALUES ($_POST)";
$insert = $pdo->prepare($sql)->execute();
if($insert){
$res = "ok";
}else{
$res = "erro";
}
return $res;
}
I wanted something like this to avoid creating a huge array or breaking it into local variables. And I wanted an opinion, this way I’m doing it is very wrong? I’m an intern and this is my first system I do alone.
I will not write as an answer because the code only works with Mysql(Mariadb does not work) and the engine has to be Innodb. Assuming the properties of
$_POST
are in the same amount as the columns of your table and the properties names are the same as the columns of your table you can insert as JSON:$sql = "INSERT INTO tbl_cliente VALUES ({json_encode ($_POST)})";
– Augusto Vasques
If you used Prepared Statment, which is even safer than what you’re doing today, you could just do something like
$stmt->bind_param("ssssssssssssss", ...$_POST)
.– Inkeliz
Yes yes, I did that way, thank you very much.
– Matheus costa