Header does not work

Asked

Viewed 51 times

2

Boa Pessoal,

I have a php file that is named after filling a form in an html file. The function of this php file is to add data to the database and after inserting it has the following code:

if(mysqli_query($con, $sql)){
	echo "<script>
             alert('Inscrição realizada'); //alerta1
     </script>";
      header('Location: ../register.htm');
	}
	else{
		echo "<script>
             alert('Inscrição não realizada'); 
     </script>";
	 header('Location: ../register.htm');
	 }

But after clicking on Submit does not show alert1 nor goes to the page I am telling you to go to. Does anyone know how this is resolved? And someone knows how to go back to the page of form but leave text boxes blank?

  • How is the TAG <form> of your HTML ?

  • 1

    It seems that the query is returning an error and falling into Else, comment the line of header to take the test. On Else add the line echo mysqli_error($conexao);

  • Now there is no error simply this inserts into the database, goes to the page and does not give me the alert

1 answer

2


Friend, the function header PHP only works when it is placed before any output to the client.

That is, codes like this below will result in error:

<?php

$meus_dados = [1, 2, 3];

foreach($meus_dados as $dado) {
    echo $dado; // saída de dados
}

header('Location: anterior.php'); // Isso resulta em erro pois já houve uma saída

Although not a good practice, if what you need is to redirect after the alert, you can use document.location javascript.

  if (mysqli_query($con, $sql)) {
      echo "<script>
             alert('Inscrição realizada'); //alerta1
             document.location.href = '../register.htm';
           </script>";

    }
  • Thank you very much Wallace was really desperate because he didn’t know you could do that. And if there is another method I do not know because I did not know of another method besides the header.

Browser other questions tagged

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