Virtual Open Schooling Online courses available at Virtual Open Schooling (VOS), for more details kindly click here!
NIOS Silver Jubilee Year
NIOS

Insert Into Statement

From NIOS
Jump to: navigation, search
Previous Page Home Page Next Page
ICT Applications

INSERT INTO statement is used to add new records to a database table.


Syntax

INSERT INTO table_name (column1,column2, column3,...)

VALUES (value1, value2,value3,...)


Example

In the last section we created a tablenamed "Contacts", with four columns; "Firstname","Lastname" and "Phone". The following exampleadds two new records to the "Contacts" table:


<?php

$con =mysql_connect("localhost","userid","abc123");

if (!$con)

{

die('Could not connect: ' .mysql_error());

}

mysql_select_db("my_db",$con);

mysql_query("INSERT INTOContacts (FirstName, LastName, Age)

VALUES ('Ajay', 'Kumar',654321)");

mysql_close($con);

?>


Insert Data From a Form Into a Database

Now we will create an HTML form thatcan be used to add new records to the "Contacts" table.


Here is the HTML form:


<html>

<body>

<formaction="insert.php" method="post">

Firstname: <inputtype="text" name="firstname" />

Lastname: <inputtype="text" name="lastname" />

Phone:<inputtype="text" name="phone" />

<input type="submit"/>

</form>

</body>

</html>


When a user clicks the submit button inthe HTML form in the example above, the form data is sent to"insert.php".


The "insert.php" fileconnects to a database, and retrieves the values from the form withthe PHP $_POST variables.


Then, the mysql_query() functionexecutes the INSERT INTO statement, and a new record will be added tothe "Contacts" table.


Here is the "insert.php"page:


<?php

$con =mysql_connect("localhost","userid","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());

}

mysql_close($con);

?>


Previous Page Home Page Next Page
ICT Applications