Wednesday, December 9, 2009

12:27 PM
When data is put into a MySQL table it is referred to as inserting data. When inserting data it is important to remember the exact names and types of the table's columns.

There are 2 ways to insert the data into the database.


Way 1:


INSERT INTO table_name
VALUES (value1, value2, value3,...);



Here, there is no need to put the exact column name for each and every data.


Way 2:


INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);



Here, the value1 is stored in column1, value2 is stored in column2.. Like wise the data are inserted into the database.


Example:


$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);





We can also insert the data from the html form itself. An example for insert the data into mysql from html form is described below:



Firstname:
Lastname:
Age:



By using the following PHP code to get the data from the HTMl form and insert into database.


$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);


0 comments: