PHP : MySQL INSERT Statement

The MySQL INSERT INTO statement is used to insert new records in a database table.

Syntax

The INSERT INTO command is used to insert data in MySQL table. Following is the syntax:
INSERT INTO table_name ( field1, field2,...fieldN )VALUES ( value1, value2,...valueN );

To insert string data types, it is required to keep all the values into single or double quotes.

Steps

  • First we will create a database server connection using mysqli_connect (See detail in the previous chapter).
  • We can insert new records in table using above INSERT INTO command/statement.
  • After query, mysqli_close() can be used to close the connection.
<?php
/**
 * Create Database Connection
 */
 
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
$database_name = 'student';
 
// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password, $database_name);
 
// If $conn is false, connection is failed
if (!$conn ) {
  die("Failed to connect to MySQL: " . mysqli_connect_error());
}
 
echo "Database Connected Successfully. <br />";
 
?>
<?php
/**
 * Insert data into Table
 */
 
require_once('db-connection.php');
 
// Mysql query to insert record into table
$mysql_query_statement = "INSERT INTO users (name, mobile, email)
	VALUES ('Ram', '9898989898', 'ram@gmail.com'),
	('Sanjay', '9898969696', 'sanjay@gmail.com'),
	('Pankit', '9898979797', 'pankit@gmail.com')";
$result = $conn->query($mysql_query_statement);
 
if ($result === TRUE) {
	echo "Records inserted successfully.";
}
else {
	echo "Error inserting records: " . $conn->error;
}
 
//Connection Close	
mysqli_close($conn);
?>

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.