PHP – Redirect URL After Form Submission

Remember about the PHP form which inserts the entry to database after form submission? Simple PHP + MySQL form with radio button and dropdown list

So now, i would like to redirect the browser to my home page after the database insertion. In PHP, redirection can be done by adding the following line add the beginning of the .php.

header("Location: https://ykyuen.wordpress.com");

But this doesn’t work in the update.php

<?php
	... your code ...

	$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
	$query.="'".$english_name."', ";
	$query.="'".$tel_number."', ";
	$query.="'".$email_address."', ";
	$query.="'".$gender."', ";
	$query.="'".$age."', ";
	$query.="'".$region."')";

	mysql_query($query) or die ('Error updating database');

	echo "Record is inserted.";

	header("Location: https://ykyuen.wordpress.com");
?>

This returns the error
Record is inserted.
Warning: Cannot modify header information – headers already sent …

The work around is making use of the ob_start() and ob_end_flush() functions. Add them in the update.php.

<?php
	ob_start();
	... your code ...

	$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
	$query.="'".$english_name."', ";
	$query.="'".$tel_number."', ";
	$query.="'".$email_address."', ";
	$query.="'".$gender."', ";
	$query.="'".$age."', ";
	$query.="'".$region."')";

	mysql_query($query) or die ('Error updating database');

	echo "Record is inserted.";

	header("Location: https://ykyuen.wordpress.com");
	ob_end_flush();
?>

The content of the output buffer would be sent only when ob_end_flush() is reached.

Done =)

Advertisement

4 thoughts on “PHP – Redirect URL After Form Submission”

  1. Actually it does redirect, it includes the page that i want to go to into the current page, so both are appearing in one page

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.