Insert data in Mysql using Php Form

In this tutorial I am going to show you how to insert data in mysql using php form. This is a basic tutorial for every PHP beginner because in almost every PHP application there is form. So I am going to create one simple form with two fields. I will not apply any PHP validation in this tutorial. It is just a simple insertion of data.

insert data into mysql using php form

First make sure you have xampp or wampp on your system. I am personally using xampp in my windows 7 machine. If you don’t have xampp in your machine. Check my post how to install xampp on local machine.

How to fetch data from Mysql using PHP

Step 1: Create Database

First you have to create database in your phpmyadmin. If you are running xampp on default ports then your phpmyadmin address should be http://localhost/phpmyadmin. In this tutorial I am creating database name as demo

phpmyadmin create database

Step 2: Create Table

In step 2, you need to create table in demo database. Table name must be posts with 4 fields i.e. id, post_title, post_content, created.

Step 3: Create Database Connection

After completion of first 2 steps, 3rd step is to create database connection in file. mysqli_connect() function is used to establish a connection with mysql database.


Step 4: Form HTML

In this step I will create 1 input field name as title and one textarea name as post_content. Both fields have required attribute which means form will not save until title and post_content have any text. In form tag action attribute is empty (action=””) which means form will be posted on the same page and method=”post” which means data is sensitive and will not show in url. For more details on form post method visit POST(HTTP).

Step 5: Apply CSS

In this step I add some css to the html tags for better look.

Step 6: Get Title and Post Content values and save them in mysql

After form submission I get title and post_content values and save them in $postTitle and $postContent variable. $created is using a php built-in date function which returns date and time. $sql is a mysql insert statement. $result is using mysqli_query function which takes 2 paramter first one is database connection and second is sql query. mysqli_query() function runs sql statement. If data will save then it will print “Post has been saved successfully“. Otherwise it will print “Unable to save post”.

Step 7: All together

 

Posted in PHP

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.