PHP: How to auto redirect page after form submission to database

    PHP: How to auto redirect page after form submission to database

    This tutorial will teach you how to auto redirect page to another page either HTML page or PHP page after submitting a form to MySQL database.

    Assuming you have your index.php file with the forms. You want to submit the form to a MySQL database and then redirect page to a success.php page

    First the form need to pass through the send.php which has the database submission codes, then redirect to success.php which is the Thank You page

    Usually a simple header location may do the trick, but most often it ends up giving an error “Warning: Cannot modify header information – headers already sent”

    header('Location: success.php');

    NOTE: The form action="send.php" passes through send.php

    <form name="register" id="register" method="POST" action="send.php" enctype="multipart/form-data" >

    In the send.php you have the below code to insert to the database then redirects


    if ( isset($_POST['submit']) ){
    //Database Connection
    global $connection;
    //Get the info from the submited post
    $Username = $_POST['Username'];
    $Password = $_POST['Password'];

    //Prevent SQL Inject
    $Username = mysqli_real_escape_string ($connection, $Username);
    $Password = mysqli_real_escape_string ($connection, $Password);

    ob_start();
    $query = "INSERT INTO loyal_members ( Username,Password,)

                VALUES ('$Username','$Password')"; $result = mysqli_query($connection, $query);
    if($result){ header('Location: success.php');

             }       

            else       

              {  echo(" Error description: " . mysqli_error($connection));  }
    ob_end_flush();
    }

    As stated above, usually even the header location can return an error page, so to get around this we use of the ob_start() and ob_end_flush() functions. Those functions are wrapped around the INSERT query.

    The information of the output buffer will be sent only when ob_end_flush() is reached.

    After the data is Inserted into the database the page will redirect to success.php with a THANK YOU

    I hope you find this tutorial helpful. Please leave comments below if you have any issues or want to contribute to this PHP redirect page tutorial.

    up