Open In App

How to pass form variables from one page to other page in PHP ?

Last Updated : 31 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Form is an HTML element used to collect information from the user in a sequential and organized manner. This information can be sent to the back-end services if required by them, or it can also be stored in a database using DBMS like MySQL. Splitting a form into multiple steps or pages allow better data handling and layering of information. This can be achieved by creating browser sessions. HTML sessions are a collection of variables that can be used to maintain the state of the form attributes while the user switched between the pages of the current domain. Session entries will be deleted as soon as the user closes the browser or leaves the site.

Syntax:

<?php
     session_start();
     session_register('variable_name');
     $_SESSION['variable_name']=variable_value;
?>

Example: This example will illustrate the steps to create a three-paged form using PHP and Browser Sessions. It is in reference to a coaching institute’s registration form. The first page of the form will be asking the user to enter their name, email and mobile number, which will be transferred to another PHP page. Where the information will be stored into session directories.

  • Code 1: Start your localhost server like Apache, etc. Complete writing the HTML tags and write the below code inside the BODY section. Save the file with the format ‘form1.php’ in the local directory of your localhost. Open your web browser and type your localhost address followed by ‘\form1.php’.




    <form method="POST" action="form2.php">
        <pre>Name: <input type="text"
            name="user_name">
        </pre>
          
        <pre>Email Address: <input type="text"
            name="user_email_address">
        </pre>
          
        <pre>Mobile Number: <input type="number"
            name="user_mobile_number">
        </pre>
          
        <input type="submit" value="Next">
    </form>

    
    

  • Output: It will open your form like this, asked information will be passed to the PHP page linked with the form (action=”form2.php”) with the use of the POST method. In the next step, submitted information will be stored in the session array.
    Output Of First Code
  • Code 2: Repeat the process of saving the file as explained above. Use the file name ‘form2.php’. When you will click ‘Next’ on form1.php page. This page will be asking the college/company name, city, state user is in, and the course he/she is applying for.




    <?php
      
    // Initialize the session
    session_start();
           
    // Store the submitted data sent
    // via POST method, stored 
      
    // Temporarily in $_POST structure.
    $_SESSION['name'] = $_POST['user_name'];
      
    $_SESSION['email_address']
            = $_POST['user_email_address'];
      
    $_SESSION['mobile_number']
            = $_POST['user_mobile_number'];
               
    ?>
      
    <!-- Form for other details-->
    <form method="POST" action="form3.php">
           
        <pre>
            Company/College: 
            <input type="text" name="college_name">
        </pre>
          
        <pre>
            City: 
            <input type="text" name="city">
        </pre>
          
        <pre>
            State: 
            <input type="text" name="state">
        </pre>
               
        <pre>
            You're a: 
            <input type="radio" name="profession"
                    value="Student">Student
              
            <input type="radio" name="profession"
                    value="Working Professional">
                    Working Professional
        </pre>
           
        <pre>
            Course: 
            <select name="course">
                <option value="DSnA">
                    Data Structures and Algorithms
                </option>
                  
                <option value="Gate_test">
                    GATE Mock Test
                </option>
                  
                <option value="Mock_interview">
                    Mock Interviews
                </option>
                  
                <option value="Machine_learning">
                    Machine Learning
                </option>
            </select>
        </pre>
        <br>
               
        <pre>
            <input type="checkbox" 
                name="terms_and_conditions"
                Terms and Conditions 
        </pre>
        <br>
          
        <input type="submit" value="Register">
       
    </form>

    
    

  • Output: It will be redirected you to this page, which will look like this:
  • Code 3: In this step, we will be extracting the information from the session array and storing it on our MySQL Database. Make a third file named ‘form3.php’ and write the following code inside the BODY section, and apply the necessary HTML tags.




    <?php
        //Initializing the session
        session_start();
          
        //writing MySQL Query to insert the details
        $insert_query = 'insert into subscriptions (
                        name,
                        email_address,
                        mobile_number,
                        college_name,
                        city,
                        state,
                        profession,
                        course,
                        terms_and_conditions,
                        ) values (
                        ' . $_SESSION['name'] . ",
                        " . $_SESSION['email_address'] . ",
                        " . $_SESSION['mobile_number'] . ",
                        " . $_POST['college_name']. ",
                        " . $_POST['city']. ",
                        " . $_POST['state']. ",
                        " . $_POST['profession']. ",
                        " . $_POST['course']. ",
                        " . $_POST['terms_and_conditions']. "
                        );"
      
        //let's run the query
        mysql_query($insert_query);
        ?>
    <pre>Successfully Registered</pre>

    
    

  • Output: On clicking Register on page 2, it will redirect you to this page where your data will be submitted into the database. As a prerequisite, you have to link your page to a MySQL database. For that, you may refer this
    Final Result

Conclusion: Sessions can be used to keep form data active until either the browser is closed or the site is left. Please note that while writing the final query, we have used data from the $_SESSION array, and also data from the $_POST array, that was posted from the last step of the form.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Previous Article
Next Article

Similar Reads

How to pass data from one component to other component in ReactJS ?
In React, passing data from one component to another component is a common task. It helps build a dynamic and interactive web application. We can pass data in components from parent to child, child to parent, and between siblings as shown below. Table of ContentPassing data from Parent to ChildPassing data from Child to Parent ComponentPassing data
5 min read
How to pass PHP Variables by reference ?
By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn't have any effect on either of the variables. Example: &lt;?php // Function used for assigning new //
2 min read
How to pass variables and data from PHP to JavaScript ?
In this article, let's see how to pass data and variables from PHP to JavaScript. We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie wo
2 min read
How to pass JavaScript variables to PHP ?
JavaScript is the client side and PHP is the server-side script language. The way to pass a JavaScript variable to PHP is through a request. Below are the methods to pass JavaScript variables to PHP: Table of Content Using GET/POST methodUsing Cookies to store informationUsing AJAXUsing GET/POST methodThis example uses the form element and GET/POST
4 min read
Pass by Value and Pass by Reference in Javascript
In this article, we will talk about Pass by Value and Pass by Reference in JavaScript. Pass By ValueIn Pass by value, the function is called by directly passing the value of the variable as an argument. So any changes made inside the function do not affect the original value.In Pass by value, parameters passed as arguments create their own copy. So
4 min read
How to pass variables to the next middleware using next() in Express.js ?
The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2] request.mydata = someData; -------&gt; let dataFromMiddleware1 = request.mydata; Installation of Express m
2 min read
How to Pass variables to JavaScript in Express JS ?
Express is a lightweight framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. When working with Express.js you may encounter scenarios where you need to pass variables from your server-side code
2 min read
How to Assign Multiple Variables in One Line in PHP ?
In PHP, assigning multiple variables in one line can be a handy and efficient way to streamline your code. This technique not only makes your code more concise but also improves readability. There are several approaches to achieve this, each with its own syntax and use cases. Table of Content Using Multiple AssignmentUsing list() FunctionUsing expl
2 min read
React.js Blueprint Variables Font variables
In this article, we will learn about the Font Variables offered by the blueprint.js library. BlueprintJS is a React-based UI toolkit for the web. It is written in Typescript. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications that run in a modern web browser. Font Variables: T
3 min read
Less.js Variables Properties as Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read