Home>

The insert into statement is used to insert new records into a database table.

Inserting data into a database table

The insert into statement is used to add new records to a database table.

grammar:

insert into table_name
values ​​(value1, value2, ......)

You can also specify the columns in which i want to insert data:

insert into table_name (column1, column2, ...)
values ​​(value1, value2, ......)

Note:sql statements are not case sensitive.insert into is the same as insert into.

In order for php to execute the statement,We must use the mysql_query () function. This function is used to send a query or command to a mysql connection.

example:

In the previous chapter,We created a table named "persons" with three columns:"firstname", "lastname" and "age". We will use the same table in this example.The following example adds two new records to the "persons" table:

<?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 persons (firstname, lastname, age)
values ​​("peter", "griffin", "35") ");
mysql_query ("insert into persons (firstname, lastname, age)
values ​​("glenn", "quagmire", "33") ");
mysql_close ($con);
?>

Insert data from the form into the database:

Now we create an html form that inserts new records into the "persons" table.

This is this html form:

<html>
<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>
</html>

When the user clicks the submit button in the html form in the example above,The form data is sent to "insert.php". "insert.php" file connects to the database,And retrieve the value from the form via the $_post variable.The mysql_query () function then executes an insert into statement and a new record is added to the database table.

Here is 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 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)
?>
php
  • Previous Explain Java generics in detail
  • Next Summary of ThinkPHP data manipulation methods