To learn more about SQL, please visit our SQL Tutorial.
In order for PHP to execute the above statement, we must use the mysql_query () function. This feature is used to send a MySQL connection to a query or command.
For example
In the previous chapter we also created a table named "People" with three columns; "Surname", "surname" and "era"
。 We will use the same table in this example. The following example adds two new records to the "People" 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);
? >
Inserting data from form to database
Now we will create an HTML form that can be used to add new records to "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"/>
Type= "Submit"/>
</form>
</body>
When the user clicks on the Submit button HTML form in the example above, the data is sent to "insert.php".
The "insert.php" file connects to a database and retrieves the form of the value with PHP's $ _post variable.
Then the INSERT INTO statement executed by the mysql_query () function, and a new record is added to the person's seat.
This 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)