Nothing like separating things into different files. See this structure:
+Projeto
---formulario.php
---salvar_formulario.php
---erro.php
In the archive php form. is the submitted form:
Then when the above form is submitted, the page will be called salvar_formulario.php, which will basically do the operation of saving the data sent by the form in the database, and after saving redirect to somewhere (at your discretion). Then stay:
<?php
if(isset($_POST['enviar']) && $_POST['enviar'] == "send"){
$sql = mysqli_query($conexao," INSERT INTO Comentarios
(Nick, Email, Site, Comentario, Identificacao, Moderacao)
VALUES ('$Nick', '$Email', '$Site', '$Comentario',
'$Identificacao', '$Moderacao')");
//verifica se foram inseridos registros no banco
if(mysqli_affected_rows($conexao) > 0){
header('Location: formulario.php');
}else{
header('Location: erro.php');
}
}
With this after filling out the form you will be redirected to the file salvar_formulario.php, and again redirected to the file php form. if the insertion is successful, or for the error.php file if an error occurs while inserting in the database.
This is known as Post/Redirect/Get.
Another option would be to make the form Submit using ajax. Using the fetch api, your php form. would look like this:
<form action="salvar_formulario.php" method="post">
<input type="text" name="algum_nome">
<button id="salvar" name="enviar">Salvar</button>
</form>
<script>
var enviar = document.getElementById('salvar');
//adiciona evento de click no botão salvar
enviar.addEventListener('click', function(){
enviarForm();
});
function enviarForm(){
//pega os dados do formulario
var form = new FormData(document.querySelector('form'));
fetch("/salvar_formulario.php", {
method: "POST",
body: form
}).then(function(resposta) {
return response.text();
})
.then(function(resposta) {
alert(resposta);
});
}
</script>
Already the file salvar_formulario.php would be changed to:
<?php
if(isset($_POST['enviar'])){
$sql = mysqli_query($conexao," INSERT INTO Comentarios
(Nick, Email, Site, Comentario, Identificacao, Moderacao)
VALUES ('$Nick', '$Email', '$Site', '$Comentario',
'$Identificacao', '$Moderacao')");
//verifica se foram inseridos registros no banco
if(mysqli_affected_rows($conexao) > 0){
echo 'Salvo com sucesso';
}else{
echo 'erro ao salvar';
}
}
Hello, one way to solve this is by giving a Header('Location:pagina.php'),going back to the page,but I don’t know if this is the best way.
– saidmrn