2

I'm trying to post data from a form with insert.php as the action. However, I cannot redirect back to the index.php once the data has posted to the database.

I've searched through the following sites to find the answer:

as well as ten stackoverflow questions on the subject.

Here is the code for the insert.php file:

<?php 
include 'connect.php';
$id = $_POST['id']; 
$idea = mysql_real_escape_string($_POST['new_idea']); 

if(!$_POST['submit']) {
    echo "Please fill out the form!"; 
    header('Location: index.php'); 
} else {
    mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error()); 
    echo "Idea has been added!"; 
    header('Location: index.php'); 
}?> 

From what I've gathered, the header() function won't execute if there's text output before it. I've tried this function without the echo "Idea has been added!"; and echo "Please fill out the form!";, but I still don't get a redirect.

Thanks in advance for your advice.

-MF

2
  • Header should be before any output. Commented Nov 29, 2012 at 5:57
  • make sure you dont have like a blank line or empty space at the top of your file, or any other files you require( ) or include( ) Commented Nov 29, 2012 at 5:58

4 Answers 4

6

From PHP documentation :

header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

And in your case, you are using echo before header()

Sign up to request clarification or add additional context in comments.

1 Comment

This answer encapsulates the main problem. Use @diEcho's answer to get around this issue.
4

work around method : use ob_start() at the top of the page

other method : Please omit any white space before starting <?php or after ?> in the page and also use exit() just after header()

1 Comment

@Michael its all my pleasure to help :)
1

Try this

<?php 
 include 'connect.php';
 $id = $_POST['id']; 
 $idea = mysql_real_escape_string($_POST['new_idea']); 

 if(!$_POST['submit']) {
    $message = "Please fill out the form!"; 
    header('Location: index.php?message='.$message); exit;
 } else {
    mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error()); 
    $message = "Idea has been added!"; 
    header('Location: index.php?message='.$message); exit;
 }?> 

Pass the error message to index.php and display it there.

Comments

0

Don't print your output before header(). Store your data into session or pass it through URL. Try this will surely help you .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.