PHP code to add data in database

The sample tutorial on how to insert data to the MySQL database is a basic function that will add data into database coming from user input in the HTML form. This tutorial can help to a beginner programmer who wants to learn PHP and My SQL web database programming.

The sample code will serve as a basis on a beginner programmer on how to create simple form in HTML then, PHP code that contain instruction set on how to insert or add records to the MySQL database. Before creating the input form and the PHP code, the database is needed to be setup or created. To create a database, you need first to have a web server and a database server running. You can install and use the XAMPP, it can be download for free. 

After setting up the XAMPP you can now create your database. To create a databse, using webbrowser like google chrome, type: http://localhost/phpmyadmin/ in the browser address bar. In the create new database textbox type the name of the database for example: mydatabase, then click the create button. In the create new table on database mydatabase type the name of your table for example: persons. In the number of fields textbox type 4, then click the go button. In the textbox provided type the following fields:

Field: personID (auoto_increment, primary key)
Type: INT

Field: FirstName
Type: VARCHAR

Field:LastName
Type: VARCHAR

Field: Age
Type: INT

After creating the backend database, it is now time to create the front-end. The interface that will be use by the user in data entry to add or insert data to MySQL database can be created in HTML, and then the instruction on how the data will be inserted to database will be created using t PHP.

The HTML code:
File Name: frmAdd.html

<html>
<head>
<title>Add Persons Record</title>
<h1>Add Persons Record</h1>
<a href="http://localhost/demo/">[Home]</a>
<hr>
</head>
<body>
<form action="insert.php" method="post">
<table>
<tr>
<td>
Firstname:
</td>
<td>
<input type="text" name="firstname" />
</td>
</tr>
<tr>
<td>
Lastname:
</td>
<td>
<input type="text" name="lastname" />
</td>
</tr>
<tr>
<td>
Age:
</td>
<td>
<input type="text" name="age" />
</td>
</tr>
<tr>
<td>
<input type="submit" />
</td>
</tr>
</table>
</form>
</body>
</html>

The PHP code to insert data into MySQL database:
File Name: insert.php

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("mydatabase", $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);
?>