How to insert data to a SQL table in PHP

Hello people, today I am going to show you how to insert data to a table in SQL from PHP. We normally only see the web forms that have facilities to enter user data. We rarely think what will happen after when we click on the submit button. Today we will learn about the background process of that scenario.

Actually it’s not much difficult. You only need to have basic PHP knowledge and little bit Form interfaceknowledge about how to write a SQL query. The image in right side show you my user interface and I am not going to put the relevant code to that interface because I have given enough examples in my previous blog articles.

When you click on the Submit button it will direct to a PHP page. You can name that PHP page as you like and don’t forget to insert that name in the form action attribute or button onClick attribute. The inside of that directing PHP code is as follow.


$var_nic = $_POST[@textfieldNic];
$var_name = $_POST[@textfieldName];
$var_age = $_POST[@textfieldAge];

$selectQuery = "SELECT * FROM member_details where nic = '$var_nic'";
$selectResult = mysql_query($selectQuery) or die ("Query failed: ".mysql_error());

$insertQuery = "INSERT INTO `member_details` (`nic`, `name`, `age`) VALUES ('$var_nic', '$var_name', '$var_age')";
$insertResult = mysql_query($insertQuery)or die('Query failed: ' . mysql_error());	

// redirect to index page code here

I have used separate PHP file to define database and the constants as my previous examples. That is why include comes at the beginning. If the database has uploded successfully the redirect code part runs finally. If not an SQL error will display in your browser.

Insert data to a table is simple as that. So BYE for now🙂

About AnujAroshA

An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
This entry was posted in PHP examples. Bookmark the permalink.

One Response to How to insert data to a SQL table in PHP

  1. Pingback: How to update MySQL table in PHP | Anu's crazy world

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s