the_
the_

Reputation: 1173

PHP Redirect after Mysql Insert

Below is my mySQL insert:

$sql="INSERT INTO gj (name, phone, city, zipcode, description, dateadded, website, address1, other2, payment_options, Products, email,cat1,cat2,cat3)
    VALUES
    ('$companyname','$phone','$city','$zipcode','$description',curdate(),'$website','$address','$other','$payment','$products','$email','$select1','$select2','$select3')";

    if (!mysql_query($sql,$link))
      {
      die('Error: ' . mysql_error());
      }
    echo "<br/><h2><font color='green' style='font-size:15px;float:right'>1 business added</font></h2>";

    mysql_close($link);
}

    ?>

Now, instead of displaying "1 business added" in green, I'd like to redirect back to the page I was on before. Thanks.

Upvotes: 2

Views: 22097

Answers (3)

Jim
Jim

Reputation: 73936

If your script is always intended to go to the same place afterwards, then you can hard-code the location. For example:

header("Location: http://www.example.com/");

Note that per RFC 2616 (the HTTP/1.1 specification), the value of the Location header must be an absolute URI, not just a path.

If your script is for a specific purpose and always redirects to a certain section, but may vary which particular records are shown, then you can incorporate the data that was posted to your script into the URL. For example:

header("Location: http://www.example.com/widgets/" . urlencode($_POST['id']));

If your script is used in several different ways, then you can pass along the URL to redirect to from the page that posts to it in a hidden form field, for example:

<input type="hidden" name="redirect-url" value="http://www.example.com/">

More generally, you should follow the Post/Redirect/Get pattern.

Upvotes: 4

Stuart
Stuart

Reputation: 1178

Add:

header("Location: page_you_want.php");

after your query has completed but before anything is echo'ed. You can only use the above code if headers have not already been sent including HTML etc.

Upvotes: 2

Toby Joiner
Toby Joiner

Reputation: 4376

I would do:

header('Location: ' . $_SERVER['HTTP_REFERER']);

after

mysql_close($link);

Upvotes: 0

Related Questions