Client views html form for data entry. After entering data, when he clicks on submit button, data transfers to PHP form (which works as mediator) and then through this PHP form data finally submits in database. So, first we will write one html file and one php file for this. Open your notepad for writing html code and save it with .html extension. We have following sample code for this html page. This page will have three text boxes for user's firstname, lastname and age and there will be one submit button.
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>
Note: Make sure to give exact file name of your php file in action clause of <form> tag such as in this example i will be using insert.php file so i am supposed to give same file name here in html file.
Note: Make sure to give exact file name of your php file in action clause of <form> tag such as in this example i will be using insert.php file so i am supposed to give same file name here in html file.
PHP file to insert data in database:
<?php
$con = mysql_connect("localhost","root","")
or die('Could not connect: ' . mysql_error());
mysql_select_db(“againtest", $con); //you have to select database first then write insert command.
$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"; // echo is builtin function used to display message in browser
mysql_close($con)
?>
Note: To get PHP to execute the statement, use the mysql_query() function. This function
is used to send a query or command to a MySQL connection.
No comments:
Post a Comment