Insert into for storing MySQL Data in PHP
The insert statement is used to insert a new record table.
Insert data to a database table
The insert statement is used to add new records to the database table.
Syntax
It may be written into two forms.
First, data without specific column names will be inserted, only their values:
INSERT INTO table_nameVALUES (value1, value2, value3,...)
The second form specifies the column name and value insert:
INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)
For more information about SQL, see our SQL tutorial.
To allow PHP to execute the preceding Declaration, we must use the mysql_query () function. This function is a MySQL connection used to send queries or commands.
For example
In the previous chapter, we created a table named "by", with three columns: "last name", "Last Name", and "times"
. We will use the same table in this example. The following example adds two "persons" tables with new records:
<?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 form to database
Now we will create an HTML form that can be used to add new records, "people" seated.
The following is an HTML form:
<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>
When the user clicks the submit button, the HTML form is sent to "insert. php" in the preceding example ".
The "insert. php" file connects to a database and retrieves the value form with the PHP $ _ POST variable.
Then, the insert into statement executed by the mysql_query () function and a new record will be added to the "person" seat.
Here is 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)?>