How to Insert Data Into MySQL Database Using PHP

INSERT :

The INSERT INTO statement is used to add new records to a MySQL table .

Syntax :

NSERT INTO table_name (column1, column2, column3,…)
VALUES (value1, value2, value3,…)

PHP MySQL INSERT Query :

SQL query using the INSERT INTO statement with appropriate values, after that we will execute this insert query through passing it to the PHP Mysqli_query function to insert data in table.

We using the following file for insert data in MySQL:

  • Database.php: For connecting data base
  • Insert.php: for getting the values from the user

Example :

CREATE TABLE user_info

( employeeId INT (200),

empname VARCHAR(200),

PASSWORD VARCHAR (200) );

Database.php :

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tel";

$employeeid=$_GET["employeeid"];
$EmployeeName=$_GET["EmployeeName"];
$Password=$_GET["Password"];


// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_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>


Alternative Code :

<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “tel”;

$employeeid=$_GET[“employeeid”];
$EmployeeName=$_GET[“EmployeeName”];
$Password=$_GET[“Password”];

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}

$sql = “INSERT INTO user_info (employeeId ,empname, PASSWORD) VALUES ($employeeid,’$EmployeeName’,’$Password’)”;

if (mysqli_query($conn, $sql)) {
echo “New record created successfully”;

} else {
echo “Error: ” . $sql . “
” . mysqli_error($conn);
}

mysqli_close($conn);
?>

Leave a Reply