Insert Data Into MySQL Using PHP


For insert data in MySQL first we have to create a table in data base.

Here we using 3 file for insert data in MySQL:

CREATE TABLE `employee` (
	`userid` int(8) NOT NULL,
	`first_name` varchar(55) NOT NULL,
	`last_name` varchar(55) NOT NULL,
	`city_name` varchar(55) NOT NULL,
	`email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

database.php

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

insert.php

<!DOCTYPE html>
<html>
  <body>
	<form method="post" action="process.php">
		First name:<br>
		<input type="text" name="first_name">
		<br>
		Last name:<br>
		<input type="text" name="last_name">
		<br>
		City name:<br>
		<input type="text" name="city_name">
		<br>
		Email Id:<br>
		<input type="email" name="email">
		<br><br>
		<input type="submit" name="save" value="submit">
	</form>
  </body>
</html>

process.php

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

Alternative Code in (PDO)

<?php
$servername='localhost';
$username='root';
$password='';
$dbname = "crud";
try {
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $city_name = $_POST['city_name'];
    $email = $_POST['email'];
    date_default_timezone_set("Asia/Calcutta");
    $insertdate = date("Y-m-d H:i:s");
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    /* set the PDO error mode to exception */
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $sql = "INSERT INTO employee (first_name,last_name,city_name,email,datetime)
    VALUES ('$first_name', '$last_name','$city_name','$email','$insertdate')";
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
echo $sql . "<br>" . $e->getMessage(); }
$conn = null; ?>


Fatal error: Cannot redeclare validate_input() (previously declared in /www/wwwroot/studentstutorial.com/demo/conn/conn.php:36) in /www/wwwroot/studentstutorial.com/demo/conn/conn.php on line 36