The INSERT INTO statement inserts a new record into a table in a database.
Inserting data into a database table
Insert into works by inserting a new record into a table in a database.
Grammar
INSERT INTO table_name
VALUES (value1, value2,....)
You can insert data in the specified column, as follows:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
NOTE: SQL statements are "letter case insensitive" statements (which do not differentiate between uppercase and lowercase letters), i.e. "insert into" and "insert into" are the same.
To create a database in PHP, we need to use the above statement within the mysql_query () function. This function is used to send a MySQL database connection to establish the request and instruction.
Case
In the previous chapter, we created a table named "person" that contained three columns: "Firstname", "Lastname", and "age." In the following case, we'll also use the same table and add two new records to it:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}mysql_select_db("my_db", $con);mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");mysql_close($con);
?>
Insert data from a table into the database
Now we'll create an HTML form where we can add a new record to the person table.
This HTML form is shown below:
<body><form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form></body>
In the above case, when a user clicks on the "Submit submit" button in the HTML form, the data in the form is sent to "insert.php". The "insert.php" file connects to the database and gets the data from the form through a PHP $_post variable, at which point the mysql_query () function executes the INSERT INTO statement so that a new record is added to the database's form.
Next, try the code for the "insert.php" page:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}mysql_select_db("my_db", $con);$sql="INSERT INTO person (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)
?>