Form submission to Database using PHP

step 1: Create a sample contact form

Index.php File:

<h4>A small example page to insert some data in to the MySQL database using PHP</h4>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />

step 2: create a database .For Ex: contact_db.Create a table for contact db.

step 3: To insert values in the table

 $servername = "localhost";
 $username = "root";
 $password = ""; 
 $dbname = "contact"; 

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

$sql = "INSERT INTO contact (firstname, lastname)
VALUES ('$_POST[fname]','$_POST[lname]')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;


step 4: Run in your browser Index.php file and submit the form .

Leave a Reply

Your email address will not be published. Required fields are marked *