PHP POST: An Associative Array

Visual representation of PHP POST

What is $_POST in PHP?

The $_POST is an associative array of variables.

These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.

We often see web forms on different web pages to sign-up, sign-in, subscription, etc. After filling the form on those web pages, as you press the submit/save button, the data is generally sent to the server.

If the form method was used as post and target page is PHP then the form data like your name, email etc. are collected in an associative array, $_POST. For example,

$str_ name=$_POST["name"];

In the current script, you may use PHP $_POST array to get the entered information and store into the database or whatever the scenario may be. In above case, the name of the textbox field is the name.

Following are a few examples of using the PHP $_POST array with a simple web form which is followed by using this with jQuery and AJAX.

A $_POST example with a simple HTML form

  • In this example, an HTML form is created with a few fields like Name, email, password, address, and gender.
  • After entering some dummy data, press the submit button.
  • The form action is set to the same file where the form is created while the method in the <form> tag is post.
  • The entered data will be displayed by using the $_POST PHP array as follows:

PHP POST

Complete code:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
.formcls { 
    padding: 9px; 
    border: solid 1px #F0AD4E; 
    outline: 0; 
    background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #F7D19F), to(#FFFFFF)); 
    background: -moz-linear-gradient(top, #FFFFFF, #F7D19F 1px, #FFFFFF 25px); 
    box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 
    -moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 
    -webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 

    } 
#postdiv{
    margin-left: 50px;
    width:30%;
    background-color:#eee;
}   
</style>

</head>

<body>
<div>
<h1>A demo of PHP $_POST</h1>
    <form method="post" action="">
        <label for="name1">Name:</label>
        <div>
          <input type="text" class="formcls" name="postname" placeholder="Enter Your Full Name">
        </div>


        <label for="gender1">Gender:</label>
        <div>
        <select class="formcls" name="postgender">
          <option>Male</option>
          <option>Female</option>
        </select>          
      </div>      

        <label for="email1">Email:</label>
        <div>
          <input type="email" class="formcls" name="postemail" placeholder="Enter Email">
        </div>


        <label for="password1">Password:</label>
        <div>
          <input type="password" class="formcls" name="postpassword" placeholder="Password here">
        </div>


        <label for="address1" >Address:</label>
        <div>
          <input type="text" class="formcls" name="postaddress" placeholder="Full Address">
        </div>
            
         <div>
          <p><input type="submit" class="formcls" value="Submit"></p>
        </div>
    </form>
   </div> 
< ?php
$post_name=$_POST["postname"];
$post_gender=$_POST["postgender"];
$post_email=$_POST["postemail"];
$post_password=$_POST["postpassword"];
$post_address=$_POST["postaddress"];

 
if( $post_name )
 
{
 
   echo "Name entered is: ". $post_name ."<br>";
   echo "Gender:" .$post_gender ."<br>";
   echo "Email:" .$post_email ."<br>";
   echo "Password:" .$post_password ."<br>";
   echo "Address:" .$post_address ."<br>";

 
}
?>
</body>
</html>

In the above example, this is how the form tag was used:

<form method=”post” action=””>

That means, sending the submitted data by using the HTTP post method. The action=”” sets the target to the same page.

After that, a few form fields are created like:

<input type=”text” class=”formcls” name=”postname” placeholder=”Enter Your Full Name”>

The name=”postname” is the one that is accessible by using the $_POST PHP array. Similarly, other form fields can be accessed, including select dropdown by using the name of each field in PHP script.

As you submit the form, the following PHP script with $_POST is used to get the entered values:

<?php

$post_name=$_POST["postname"];

$post_gender=$_POST["postgender"];

$post_email=$_POST["postemail"];

$post_password=$_POST["postpassword"];

$post_address=$_POST["postaddress"];

if( $post_name )

{


echo "Name entered is: ". $post_name ."<br>";
echo "Gender:" .$post_gender ."<br>";
echo "Email:" .$post_email ."<br>";
echo "Password:" .$post_password ."<br>";
echo "Address:" .$post_address ."<br>";

}

?>

The data taken by using the PHP POST array is assigned to variables. Finally, those variable values are displayed on the web page.

An example of $_POST with Bootstrap form

Technically, there is no difference when accessing the values from the simple HTML form or using the Bootstrap based form.

As such, Bootstrap is a popular web framework these days, so I covered this example.

  • In this example, a web form is created by using the Bootstrap CSS classes. The same form fields are used as in the above example along with a submit button.
  • Clicking on the button will submit the form where the PHP script will use the $_POST to assign entered information to variables.
  • Finally, the entered values are displayed on the same webpage.

 

PHP- _POST Bootstrap

HTML + PHP Code

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
.formcls { 
    padding: 9px; 
    border: solid 1px #408080; 
    outline: 0; 
    background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #9DCECE), to(#FFFFFF)); 
    background: -moz-linear-gradient(top, #FFFFFF, #9DCECE 1px, #FFFFFF 25px); 
    box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 
    -moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 
    -webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 

    } 
#postdiv{
    margin-left: 50px;
    width:30%;
    background-color:#eee;
}   
</style>

</head>

<body>
<div class="container">
<h1>A demo of $_POST with Bootstrap</h1>
    <form class="form-horizontal" role="form" method="post" action="">
      <div class="form-group">
        <label for="name1" class="col-sm-2 control-label">Name:</label>
        <div class="col-sm-4">
          <input type="text" class="form-control formcls" name="postname" placeholder="Enter Your Full Name">
        </div>
      </div>
      <div class="form-group">
        <label for="gender1" class="col-sm-2 control-label">Gender:</label>
        <div class="col-sm-2">
        <select class="form-control formcls" name="postgender">
          <option>Male</option>
          <option>Female</option>
        </select>          
          
        </div>
      </div>      
      <div class="form-group">
        <label for="email1" class="col-sm-2 control-label">Email:</label>
        <div class="col-sm-5">
          <input type="email" class="form-control formcls" name="postemail" placeholder="Enter Email">
        </div>
      </div>
      <div class="form-group">
        <label for="password1" class="col-sm-2 control-label">Password:</label>
        <div class="col-sm-3">
          <input type="password" class="form-control formcls" name="postpassword" placeholder="Password here">
        </div>
      </div>
      <div class="form-group">
        <label for="address1" class="col-sm-2 control-label">Address:</label>
        <div class="col-sm-5">
          <input type="text" class="form-control formcls" name="postaddress" placeholder="Full Address">
        </div>
      </div>            
   </div> 
        <div class="col-sm-offset-2 col-sm-5">   
        <p><input type="submit" class="btn btn-lg btn-block btn-info" value="Submit"></p>
        </div><br /><br /><br />
        <div id="postdiv"><h3>You entered following data!</h3></div>
     </form>
< ?php
$post_name=$_POST["postname"];
$post_gender=$_POST["postgender"];
$post_email=$_POST["postemail"];
$post_password=$_POST["postpassword"];
$post_address=$_POST["postaddress"];

 
if( $post_name )
 
{
 
   echo "Name entered is: ". $post_name ."<br>";
   echo "Gender:" .$post_gender ."<br>";
   echo "Email:" .$post_email ."<br>";
   echo "Password:" .$post_password ."<br>";
   echo "Address:" .$post_address ."<br>";

 
}
?>
</body>
</html>

To use the Bootstrap classes, you have to include its CSS library on the web page. This website contains a series of Bootstrap tutorials that you may read here.

As you execute this code, you can see the data displayed after you enter the information and press the submit button. The same PHP script is used to get the values of the textbox or select dropdown by using the $_POST associative array.

An example of using $_POST with jQuery AJAX’s post method

Not only data sent by using the form’s method=post is contained in the $_POST array, but any data sent by using the HTTP Post request is accessible by using the $_POST.

The jQuery’s ajax post method is used to send data by using HTTP request. This method is used to make Ajax calls, where the data is sent and returned without refreshing the web page, as happened in the above examples.

In the following example, I will include the jQuery library to use the $post method of jQuery.

A form is given to enter the same information as in above examples. However, rather than sending it by using form’s action=””, the data will be sent by using the jQuery post method.

The data sent by $post is sent in the <script> section where a PHP file is called. See the complete code and output on the demo page:

PHP- POST ajax post

Markup (HTML, CSS)

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<script>
$(document).ready(function(){
$("#postdata").click(function(){ 
    
postname=$("#postname").val();
postgender=$("#postgender").val();
postemail=$("#postemail").val();
postpass=$("#postpassword").val();
postaddress=$("#postaddress").val();


        $.post("post-forms.php", {name:postname, gender:postgender, email:postemail, password:postpass, address:postaddress },function(postresult){
        $("#postdiv").html(postresult);
        });

});
});
</script>

<style>
.formcls { 
    padding: 9px; 
    border: solid 1px #F0AD4E; 
    outline: 0; 
    background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #F7D19F), to(#FFFFFF)); 
    background: -moz-linear-gradient(top, #FFFFFF, #F7D19F 1px, #FFFFFF 25px); 
    box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 
    -moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 
    -webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px; 

    } 
#postdiv{
    margin-left: 50px;
    width:30%;
    background-color:#eee;
}   
</style>

</head>

<body>
<div class="container">
<h1>A demo of PHP $_POST with jQuery $.post</h1>
    <form class="form-horizontal" role="form">
      <div class="form-group">
        <label for="name1" class="col-sm-2 control-label">Name:</label>
        <div class="col-sm-4">
          <input type="text" class="form-control formcls" id="postname" placeholder="Enter Your Full Name">
        </div>
      </div>
      <div class="form-group">
        <label for="gender1" class="col-sm-2 control-label">Gender:</label>
        <div class="col-sm-2">
        <select class="form-control formcls" id="postgender">
          <option>Male</option>
          <option>Female</option>
        </select>          
          
        </div>
      </div>      
      <div class="form-group">
        <label for="email1" class="col-sm-2 control-label">Email:</label>
        <div class="col-sm-5">
          <input type="email" class="form-control formcls" id="postemail" placeholder="Enter Email">
        </div>
      </div>
      <div class="form-group">
        <label for="password1" class="col-sm-2 control-label">Password:</label>
        <div class="col-sm-3">
          <input type="password" class="form-control formcls" id="postpassword" placeholder="Password here">
        </div>
      </div>
      <div class="form-group">
        <label for="address1" class="col-sm-2 control-label">Address:</label>
        <div class="col-sm-5">
          <input type="text" class="form-control formcls" id="postaddress" placeholder="Full Address">
        </div>
      </div>            

    </form>
   </div> 
<div class="col-sm-offset-2 col-sm-5">   
<button id="postdata" class="btn btn-lg btn-block btn-warning">Create Account</button>
</div><br /><br /><br />
<div id="postdiv"><h3>You entered following data!</h3></div>
</body>
</html>

PHP code:

<?php

$post_name=$_POST["name"];
$post_gender=$_POST["gender"];
$post_email=$_POST["email"];
$post_password=$_POST["password"];
$post_address=$_POST["address"];

 
if( $post_name )
 
{
 
   echo "Name entered is: ". $post_name ."<br>";
   echo "Gender:" .$post_gender ."<br>";
   echo "Email:" .$post_email ."<br>";
   echo "Password:" .$post_password ."<br>";
   echo "Address:" .$post_address ."<br>";
}
?>

If you look at the code, there is no method used in the <form> tag or any action page is set, instead, it is simply given CSS class:

<form class=”form-horizontal” role=”form”>

As you press the button after entering information, at the click event of the button the $.post method of jQuery is called.

In the $.post method, the PHP file is specified along with sending information entered in the form fields:

$.post("post-forms.php", {name:postname, gender:postgender, email:postemail, password:postpass, address:postaddress },function(postresult){

$("#postdiv").html(postresult);

});

(See the <script> section in code)

In the PHP file, the $_POST array contains that information sent after using the $.post jQuery method. The information is assigned to PHP variables and displayed by using the echo statement:

$post_name=$_POST["name"];

$post_gender=$_POST["gender"];

…..

A point to be noted is the echo statement will not directly display the information. The data is returned back to $.post method’s postresult parameter. And this line in the <script> section displays the information in an HTML div:

$("#postdiv").html(postresult);

An example of using $_POST with MySQL database

  • In this example, an HTML dropdown is given to select a product. After selecting the product, press the button “Load Product Information”.
  • On the click event of the button, the $.post method of jQuery is called.
  • The $.post method calls the PHP file whereas $_POST method is used to get the value of the selected product.
  • On that basis, an SQL query is written to fetch data from the MySQL database’s table.
  • Finally, PHP returns the fetched data to $.post method which is displayed in an HTML table. See the example by clicking the link or image below:

PHP-$ POST MySQL

HTML/CSS:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js">
</script>
<script>
$(document).ready(function(){
    $("#postbtn").click(function(){ 
        var prodname = $('#selproduct :selected').text();
        $.post("postsingleprod.php", { ProductName: prodname },function(postresult){
        $("#presentprod").html(postresult);
        });
 });    
});

</script>

<style>
.demotbl {
    border: 0px solid #DE1F58;
  }
.demotbl th{
    padding:15px;
    color:#fff;
    text-shadow:1px 1px 1px #568F23;
    border-bottom:3px solid #DE1F58;
    background-color:#DE1F58;
    background:-webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0.02, rgb(222,31,88)),
        color-stop(0.51, rgb(240,147,174)),
        color-stop(0.87, rgb(248,203,217))
        );
    background: -moz-linear-gradient(
        center bottom,
        rgb(222,31,88) 3%,
        rgb(240,147,174) 52%,
        rgb(248,203,217) 88%
        );
    -webkit-border-top-left-radius:5px;
    -webkit-border-top-right-radius:5px;
    -moz-border-radius:5px 5px 0px 0px;
    border-top-left-radius:5px;
    border-top-right-radius:5px;
  }
.demotbl td{
    width:100px;
    padding:10px;
    text-align:center;
    vertical-align: top;
    background-color:#F8CBD9;
    border: 1px solid #F9D0DC;
    -moz-border-radius:2px;
    -webkit-border-radius:2px;
    border-radius:2px;
    color:#000;
    text-shadow:1px 1px 1px #fff;

  }
  
.divcls{
  background: #6A0432;
  width:420px;
  border-radius: 15px;
  padding:20px;
  font-size:18px;
  color:#fff;   
}  
</style>

</head>
<body>
 
<h3>A demo of $_POST with MySQL DB</h3>
<div class="divcls">
<label>Select a product</label>
<select id="selproduct">
     <option>Select a Product</option>
      <option value="Wheat">Wheat</option>
      <option value="Rice">Rice</option>
      <option value="Sugar">Sugar</option>  
  </select>
<button id="postbtn">Load Product Information</button>  
</div>
<div id="presentprod"></div> 
</body>
</html>


PHP

<?php
//remove space in PHP tag
//Getting product name sent by Post method
$productname = $_POST['ProductName'];

$dbhostname = 'localhost';
 
$dbusername = 'username';
 
$dbpassword = 'password';
 
$conn = mysql_connect($dbhostname, $dbusername, $dbpassword);
 
if(! $conn )
 
{
 
  die('Could not connect: ' . mysql_error());
 
}
 
//echo 'MySQL Connected successfully'."<BR>";
 
mysql_select_db("DBName") or die(mysql_error());
 
//echo "Connected to Database"."<BR>";
 
$emp_salary = 7000;
 
$emp_id = 3;
 
$sql_statemanet = "select * from tbl_products where Product_Name = '" .$productname ."'";
 
$rec_select = mysql_query( $sql_statemanet);
 
if(! $rec_select )
 
{
 
  die('Could not retrieve data: ' . mysql_error());
 
}
 
//Displaying fetched records to HTML table
 
echo "<table class='demotbl'>";
 
echo "<tr> <th>Product ID</th> <th>Product </th> <th>Quality </th> <th>Quantity </th></tr>";
 
// Using mysql_fetch_array() to get the next row until end of table rows
 
while($row = mysql_fetch_array( $rec_select )) {
 
                // Print out the contents of each row into a table
 
                echo "<tr><td>";
 
                echo $row['Product_ID'];
 
                echo "</td><td>";
                
                echo $row['Product_Name'];
 
                echo "</td><td>";

                echo $row['Product_Quality'];
 
                echo "</td><td>";
                
                echo $row['Product_Quantity'];
 
                echo "</td></tr>";                                
 
}
 
mysql_close($conn);
 
?>

 

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!