How To Insert Data Into MySQL Db Using Form In PHP Database?


You understood how to create database and tables in MySQL. so, you will learn how to execute SQL query to insert records into a table.

The INSERT INTO 'tbl_name' statement is used to insert new rows in a database table.

Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function mysqli_query. Below a simple example to insert a record into User table.

Try out following example to insert record into User table.

Stap 1

Next step, we have to create "index.php". put bellow code in this file:

Create a : /index.php

<?php 
$databaseusername = 'root';
$databasepassword = ''; // localhost may be blank.
$databasename = 'userdbname';

$conn = mysqli_connect("localhost", $databaseusername, $databasepassword, $databasename); 

if($conn === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Stap 2

In this step. put bellow code in this file:

index.php

<html>
   <head>
      <title>Add New Record in MySQL Database</title>
   </head>
   
   <body>
    <form method = "post">
        <table width = "400" border = "0" cellspacing = "1" cellpadding = "2">
            <tr>
            <td width = "100">User Name</td>
            <td><input name = "user_name" type = "text" value="User Name"></td>
            </tr>
        
            <tr>
            <td width = "100">User Address</td>
            <td><input name = "user_address" type = "text" value="User Address"></td>
            </tr>
        
            <tr>
            <td width = "100">User Salary</td>
            <td><input name = "user_salary" type = "text" value="User Salary"></td>
            </tr>
        
            <tr>
            <td width = "100"> </td>
            <td> </td>
            </tr>
        
            <tr>
            <td width = "100"> </td>
            <td>
                <input name = "submit" type = "submit" value = "Add User">
            </td>
            </tr>
        
        </table>
    </form>
   </body>
</html>
Stap 3

In this step. put bellow code in this file:

index.php

<!-- // insert query  -->


<?php 
  if (isset($_POST['submit'])) {
    $user_name= $_POST['user_name'];
    $user_address= $_POST['user_address'];
    $user_salary= $_POST['user_salary'];
    if ($user_name== '' OR $user_address == '' Or $user_salary == '') { ?>
       <script> alert('All Fields Are Required');</script>
     <?php }else{
      $sql="INSERT INTO `user`(`user_name`,`user_address`,`user_salary`) VALUES ('user_name','user_address','user_salary')";
      mysqli_query($conn,$sql);
      }
    }
 ?>

Demo:

How To Insert Data Into MySQL Database Table Using PHP

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close