Google News
logo
PHP MySQL INSERT Data
The INSERT INTO statement is used to add new records to a database table.

Here are some syntax rules to follow:
  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted
Syntax

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

MySQL 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. Here's an example,we created an empty table named "student_details" with five columns like stu_id, stu_name, college, email and mobile fields.

The following examples add a new record to the "student_details" table :

MySQLi Insert Data (Procedural)
<?php

	// Create connection
	$ftl_connect = new mysqli("localhost", "root", "", "ftl_db");
	// Check connection
	if (!$ftl_connect) {
		die("Connection failed: " . mysqli_connect_error());
	}
	
	$sql = "INSERT INTO student_details (`stu_id`, `stu_name`, `college`, `email`, `mobile`)
	VALUES ('', 'V V Ramana Reddy', 'S V Arts and Science College', 'info@freetimelearning.com', '9963666068')";
	
	if (mysqli_query($ftl_connect, $sql)) {
		echo "New record has successfully created..!";
	} else {
		echo "Error: " . $sql . "<br>" . mysqli_error($ftl_connect);
	}
	//Close Connection
	mysqli_close($ftl_connect);
	
?>
MySQLi Insert Data (Object-oriented)
<?php

	// Create connection
	$ftl_connect = new mysqli("localhost", "root", "", "ftl_db");
	// Check connection
	if ($ftl_connect->connect_error) {
		die("Connection failed: " . $ftl_connect->connect_error);
	} 
	
	$sql = "INSERT INTO student_details (`stu_id`, `stu_name`, `college`, `email`, `mobile`)
	VALUES ('', 'V V Ramana Reddy', 'S V Arts and Science College', 'info@freetimelearning.com', '9963666068')";
	
	if ($ftl_connect->query($sql) === TRUE) {
		echo "New record has successfully created..!";
	} else {
		echo "Error: " . $sql . "<br>" . $ftl_connect->error;
	}
	
	//Close Connection
	$ftl_connect->close();

?>
MySQL Insert Data (PDO)
<?php

	try {
		$ftl_connect = new PDO("mysql:host=localhost;dbname=ftl_db", "root", "");
		// set the PDO error mode to exception
		$ftl_connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$sql = "INSERT INTO student_details (`stu_id`, `stu_name`, `college`, `email`, `mobile`)
		VALUES ('', 'V V Ramana Reddy', 'S V Arts and Science College', 'info@freetimelearning.com', '9963666068')";
		// use exec() because no results are returned
		$ftl_connect->exec($sql);
		echo "New record has successfully created..!";
		}
	catch(PDOException $e)
		{
		echo $sql . "<br />" . $e->getMessage();
		}
	//Close Connection
	$ftl_connect = null;
	
?>