Pages

Subscribe:

Ads 468x60px

Friday, July 30, 2010

How to Insert Data into a Table Using MySQL Database?

During making a dynamic website, it is often needed to insert data into a database. Generally MySQL is used as the database in PHP. So, here you will see how to insert data using PHP code. For this, a practical example is given for you. Suppose, there is a form that has two text fields.

What should happen when you insert two values in both the fields and click Add button? See Image:



Answer is very simple. Just these two values should be added to the particular table in the database. Let, the database name is info and the table name is tbl_info. Then what should be the particular code? I am giving the code below. When you will click on the Add button then your current page will be redirected to another page. Suppose this page name is result.php. Now you must put this code in the result.php page. Remember that first field name is field1 and second field name is field2.



$link = mysql_connect('localhost', 'root', '') or die("Couldn't connect to the database.");
$dbname = mysql_select_db('info') or die("Couldn't select the database");
include error_reporting(0);

$f1=$_POST["field1"];
$f2=$_POST["field2"];

$sql = "INSERT INTO tbl_info (field1,field2) VALUES ('$f1','$f2')";
$res = mysql_query($sql);
if ($res)
{echo "Successfully Inserted";}
else
{echo "An error during insertion!";}
?>

Here the user name is root and password fields is left blank. But if you use web server for this code, then please the particular user name and password for those.

1 comments: