PHP MySQLi Code to Store Form Data in Database

This article is created to describe the way, to store form data or the data entered by user on the web, using PHP MySQLi object-oriented and procedural script.

Store Form Data using PHP MySQLi Object-Oriented Script

I really do not know about your requirement, on saving or storing of user (form) data in the database. I mean, what type of data, you need to store?
But here, I am going to create a form, where user fills their username along with a comment, to store in the database.

Whatever, the data you need to store, the process will be same, like shown in the example given below:

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $server = "localhost";
      $user = "root";
      $pass = "";
      $db = "fresherearth";
      
      $conn = new mysqli($server, $user, $pass, $db);
      
      if($conn -> connect_errno)
      {
         echo "Database connection failed!<BR>";
         echo "Reason: ", $conn -> connect_error;
         exit();
      }
      else
      {
         $user = $_POST["user"];
         $data = $_POST["data"];
         
         $sql = "INSERT INTO comments(user, data)
            VALUES('$user', '$data');";
         
         $res = $conn -> query($sql);
         if($res)
         {
            echo "Data inserted into the database successfully!";
            
            // block of code, to process further...
         }
         else
         {
            echo "Something went wrong!<BR>";
            echo "Error description: ", $conn -> error;
            exit();
         }
      }
      $conn -> close();
   }
?>
<HTML>
<BODY>

<FORM METHOD="POST">
   Enter Data:<BR>
   <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR>
   <TEXTAREA TYPE="text" STYLE="height:60px;" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR>
   <INPUT TYPE="submit" NAME="comment" VALUE="Submit">
</FORM>

</BODY>
</HTML>

Before executing the above example of storing form data in database, a database named fresherearth, in which, a table named comments must be available, with following fields:

php mysql store user data

All the data, should be stored in this table. Now here is the sample initial output produced by above PHP MySqLi object-oriented script to store user data/comment in the database:

php mysql save data in database

Now enter the data, say fresherearth in Username field, whereas PHP is Fun?
Is not it?
in Comment field. And then hit Submit button. Here is the output, you will see:

php mysql store data in database

Here is the snapshot of the table, customer, after executing the above script:

php mysql save user data

Note - The mysqli() is used to open a connection to the MySQL database server, in object-oriented style.

Note - The new keyword is used to create a new object.

Note - The connect_errno is used to get/return the error code (if any) from last connect call, in object-oriented style.

Note - The connect_error is used to get the error description (if any) from last connection, in object-oriented style.

Note - The query() is used to perform query on the MySQL database, in object-oriented style.

Note - The error is used to return the description of error (if any), by the most recent function call, in object-oriented style.

Note - The exit() is used to terminate the execution of the current PHP script.

Note - The close() is used to close an opened connection, in object-oriented style.

The above example, can also be created in this way:

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $conn = new mysqli("localhost", "root", "", "fresherearth");
      
      if(!$conn -> connect_errno)
      {
         $user = $_POST["user"];
         $data = $_POST["data"];
         
         $sql = "INSERT INTO comments(user, data)
            VALUES('$user', '$data');";
            
         if($conn -> query($sql))
            echo "Data inserted into the database successfully!";
      }
      $conn -> close();
   }
?>
<HTML>
<BODY>

<FORM METHOD="POST">
   Enter Data:<BR>
   <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR>
   <TEXTAREA TYPE="text" STYLE="height:60px;" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR>
   <INPUT TYPE="submit" NAME="comment" VALUE="Submit">
</FORM>

</BODY>
</HTML>

Store Form Data using PHP MySQLi Procedural Script

To store form data using PHP MySQLi procedural script, follow the example given below:

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $conn = mysqli_connect("localhost", "root", "", "fresherearth");
      
      if(mysqli_connect_errno())
      {
         echo "Database connection failed!<BR>";
         echo "Reason: ", mysqli_connect_error();
         exit();
      }
      else
      {
         $user = $_POST["user"];
         $data = $_POST["data"];
         
         $sql = "INSERT INTO comments(user, data)
            VALUES('$user', '$data');";
         
         if(mysqli_query($conn, $sql))
            echo "Data inserted into the database successfully!";
         else
         {
            echo "Something went wrong!<BR>";
            echo "Error description: ", $conn -> error;
            exit();
         }
      }
      mysqli_close($conn);
   }
?>
<HTML>
<BODY>

<FORM METHOD="POST">
   Enter Data:<BR>
   <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR>
   <TEXTAREA TYPE="text" STYLE="height:60px;" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR>
   <INPUT TYPE="submit" NAME="comment" VALUE="Submit">
</FORM>

</BODY>
</HTML>

Note - The mysqli_connect() is used to open a connection to the MySQL database server, in procedural style.

Note - The mysqli_connect_errno() is used to get/return the error code (if any) from last connect call, in procedural style.

Note - The mysqli_connect_error() is used to return the error description (if any) from the last connection, in procedural style.

Note - The mysqli_query() is used to perform query on the MySQL database, in procedural style.

Note - The mysqli_error() is used to return the description of error (if any), by the most recent function call, in object-oriented style.

Note - The mysqli_close() is used to close an opened connection to the MySQL database, in procedural style.

The examples given above, looks very simple and basic. Also the data are getting saved in the database, without even basic filter, that may be sometime malicious. Therefore, let me create another safe and secure PHP MySQLi script, that does the same job, of storing form data in database.

PHP MySQLi Safe and Secure Script to Save Form Data in Database

This example of storing user form data in database, is created using PHP MySQLi safe and secure object-oriented script.

<?php
   $conn = new mysqli("localhost", "root", "", "fresherearth");
   if($conn->connect_errno)
   {
      echo "Database connection failed!<BR>";
      echo "Reason: ", $conn->connect_error;
      exit();
   }
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      function validate($x)
      {
         $x = trim($x);
         $x = stripslashes($x);
         $x = htmlspecialchars($x);
         return $x;
      }
      $stmt = $conn->prepare("INSERT INTO comments(user, data) VALUES (?, ?)");
      $stmt->bind_param("ss", $user, $data);
      $user = validate($_POST["user"]);
      $data = validate($_POST["data"]);
      if($stmt->execute())
         echo "Your comment posted successfully!";
   }
?>
<HEAD>
<STYLE>
   .myForm{width: 380px; margin: auto; padding: 12px;}
   .myForm h2{text-align: center;}
   .myForm input, textarea{width: 100%;}
   .myForm input{padding: 8px; margin-bottom: 8px;}
   .myForm textarea{height: 80px; padding: 8px; margin-bottom: 8px;}
   button{width: 100%; background-color: #008080; color: white; font-size: 1em; padding: 12px;}
   button:hover{cursor: pointer;}
   .display{width: 380px; margin: auto; border-left: 2px solid #ccc; padding: 12px;}
   .commentBox{margin-bottom: 12px;}
   .right{text-align: right;}
</STYLE>
<HTML>
<BODY>

<DIV CLASS="myForm">
   <FORM METHOD="POST">
   <h2>Enter the Comment</h2>
      <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR>
      <TEXTAREA TYPE="text" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR>
      <BUTTON TYPE="submit">Post</BUTTON>
   </FORM>
</DIV>

<DIV CLASS="display">
<h2>Latest Comments</h2>
<?php 
   $sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 10";
   if($result = $conn->query($sql))
   {
      while($row = $result->fetch_row())
      {
         echo "<div class=\"commentBox\">";
         echo "By <B>", $row[2], "</B><BR>";
         echo $row[3];
         echo "<div class=\"right\">", $row[1], "</div>";
         echo "</div>";
      }
   }
   $conn->close();
?>
</DIV>

</BODY>
</HTML>

The output produced by above PHP example is:

php store user data in database

Now enter your username along with comment, then hit on the Post button, to post your comment on the website. For example, let me type some random anonymous username along with comment:

php mysql save data

Now click on the Post button, here is the new output:

php mysql save data in database example

Notice your latest comment, that is added on the website.

Note - The prepare() is used to prepare an SQL statement before its execution on the MySQL database, in object-oriented style, to avoid SQL injection.

Note - The bind_param() is used to bind variables to a prepared statement, as parameters, in object-oriented style.

Note - The execute() is used to execute a prepared statement on the MySQL database, in object-oriented style.

PHP Online Test


« Previous Tutorial Next Tutorial »