Nothing like separating things into different files. See this structure:
+Projeto
---formulario.php
---salvar_formulario.php
---erro.php
In the form.php file is the submitted form:
Then when the form above is submitted, it will call the save_formular.php page, which will basically save the data sent by the form to the database, and after saving redirect somewhere your criteria). Then it stays:
<?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 fill in the form you will be redirected to the save_formula.php file, and redirected again to the formular.php file if the insertion is successful, or to the error.php file in case of some error when inserting in the database.
This is known as Post / Redirect / Get .
Another option would be for you to submit the form using ajax. Using api fetch , your form.php 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>
The save_formula.php file 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';
}
}