Breaking

LightBlog

Thursday, 26 February 2015

How to insert data in database with PHP MySQL

After your table and database created you can take action for storing the data in database. Insert into statement is used for creating new record in database with PHP Script. In this command we can insert the data in database at run time. Here are some syntax rules to follow.
  • The SQL Query must be quoted in PHP.
  • Numeric values must not allow.
  • String values inside the SQL query must be quoted.
  • The word NULL must not be quoted.
                                             

Syntax: Insert into table_name (colume1, colume2, colume3) VALUES (value1, value2, value3);
There are two methods for defining insert into statement.


First method: There is no column in database where data store.
Syntax: Insert into table_name  VALUES (value1, value2, value3);
Second method: There are both column and values available in database.
Syntax: Insert into table_name (colume1, colume2, colume3) VALUES (value1, value2, value3);
Example:
<?php
mysql_connect("localhost","root","");
mysql_select_db("student");
extract($_REQUEST);
$q="INSERT INTO first (fname,address)VALUES('$fname','$address')";
mysql_query($q);
header("Location:first.php");
?>
Insert data from form into database
For inserting data from form  we need HTML form and PHP code to receive the data from  HTML form. So first we need to create HTML Form such as First.php.
<html>
<body>
<form action="process.php" method="post" enctype="multipart/form-data">
Name:<input name="fname" type="text" id="fname" />
Address:<textarea name="address" cols="" rows="" id="address"></textarea>
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>
This HTML form will send two variable fname and address to process.php file as describe in action parameter of form.
<?php
mysql_connect("localhost","root","");
mysql_select_db("student");
extract($_REQUEST);
$q="INSERT INTO first(fname,address)VALUES('$fname','$address')";
mysql_query($q);
header("Location:first.php");
?>
Adbox