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 knowledge 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.
... include("database.php"); $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🙂