How to Insert Records in PHP with MySQL Tutorial

For insert data in MySQL first we've to make a table in database.
database.php - For connecting data base
Insert.php - Getting the values from the user
Insert-process - A PHP file that process the request

 

CREATE TABLE `details` (
	`id` int(8) NOT NULL,
	`firstname` varchar(55) NOT NULL,
	`lastname` varchar(55) NOT NULL,
	`city` varchar(55) NOT NULL,
	`email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Create database.php

<?php
$servername='localhost';
$username='root';
$password='';
$dbname = "user_details";
$conn=mysqli_connect($servername,$username,$password,"$dbname");
if(!$conn){
   die('Could not Connect My Sql:' .mysql_error());
}
?>

Create insert.php file

<!DOCTYPE html>
<html>
  <body>
	<form method="post" action="Insert-process.php">
		First name:<br>
		<input type="text" name="firstname">
		<br>
		Last name:<br>
		<input type="text" name="lastname">
		<br>
		City :<br>
		<input type="text" name="city">
		<br>
		Email Id:<br>
		<input type="email" name="email">
		<br><br>
		<input type="submit" name="save" value="submit">
	</form>
  </body>
</html>

Create a insert-process.php

<?php
include_once 'database.php';
if(isset($_POST['save']))
{	 
	 $firstname = $_POST['firstname'];
	 $lastname = $_POST['lastname'];
	 $city = $_POST['city'];
	 $email = $_POST['email'];
	 $sql = "INSERT INTO details (firstname,lastname,city,email)
	 VALUES ('$firstname','$lastname','$city','$email')";
	 if (mysqli_query($conn, $sql)) {
		echo "New record insert successfully !";
	 } else {
		echo "Error: " . $sql . "
" . mysqli_error($conn);
	 }
	 mysqli_close($conn);
}
?>