Inserting data to database #

We have created two files till now

  • index.php : Form for inserting data
  • submit.php : We are printing the form data
  • db.php : MySQL and php connection

Now we will create the third file(show.php) which will insert data in database.

To insert data into the database, we have to send the SQL query to the database. We will create a dynamic SQL query based on the form data.

Build SQL query based on form data #

If you remember the Code from Getting Data from form then you must know

  • $name: It have form data value of name input field.
  • $price: It have form data value of name input field.
  • $description: It have form data value of description textarea.
$sql = "INSERT INTO `product`(`name`, `price`, `description`) VALUES ('$name', $price, '$description')";

The above code will generate a SQL query based on the form data.

Execute SQL query #

Now we will run the above sql code to mysql database. If you remember then we have a connection with the sql file. The connection object is stored in $con. We are going to run the above sql query on that object.

On Success execution of the query it return TRUE.


When you will combine both the it will insert the data in the database, based on the form.

Final Code #

Here is your final code which you can copy and paste if you want or write it by yourself by seeing it also.


        $name = $_POST['pname'];
        $price = $_POST['pprice'];
        $description = $_POST['pdescription'];

        $sql = "INSERT INTO `product`(`name`, `price`, `description`) 
                VALUES ('$name', $price, '$description')";
        // echo $sql;
        if($con->query($sql) === TRUE){
            echo "added successfully";
            echo "something went wrong";

        echo "no submit";
        // redirect to homepage

comments powered by Disqus