Insert Data into Database using PHP MySQLi

In this tutorial we will see how to Insert Data into Database using PHP MySQLi. First we create a database then table after that we start to insert data into database table using php mysqli.Mysqli is extended version of MySQL. We will use mysqli to access mysql database.

To insert data in database table we use INSERT INTO command. Here we will see both MySQLi Procedural and MySQLi Object-oriented method to connect to mysql database and insert data into database.

How to Insert Data into Database using PHP MySQLi

Read:

How to use mysqli_connect in PHP

Select Data From a Database Table Using PHP MySQLi

Database/Table

Create database name ‘demodb’ using given below sql query

CREATE DATABASE `demodb`;

Run below sql query to create a table named tbl_users

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(20) NOT NULL,
  `userEmail` varchar(50) NOT NULL,
  PRIMARY KEY (`userID`)
)

MySQLi Procedural Example

 <?php 
$db_server ="localhost";
$db_user = "root";
$db_pass = ""; $db_name ="demodb"; // Create connection
$conn = mysqli_connect($db_server, $db_user, $db_pass, $db_name); // Check connection
if($conn===false) { die("Could not connect::". mysqli_connect_error()); }

$sql = "INSERT INTO tbl_users(userName,userEmail) VALUES('vikash','vikash@phpcluster.com')";
if(mysqli_query($conn, $sql)) { echo "Records added successfully";
}
else { echo "error" .mysqli_error($conn); } mysqli_close($conn);
?>

MySQLi Object Oriented Example

<?php 
$db_server ="localhost";
$db_user = "root";
$db_pass = "";
$db_name ="demodb"; // Create connection
$conn = new mysqli($db_server, $db_user, $db_pass, $db_name); //check connection
if($conn-> connect_error) {
die("Could not connect:". $conn->connect_error);
}
$sql = "INSERT INTO tbl_users(userName,userEmail) VALUES('vikash','vikash@phpcluster.com')"; if($conn->query($sql)===true)
{
echo "Records added succesfully";
} else {
echo "error" .$conn->error;
} $conn->close();
?>

 So you have learned about how to access database using PHP MySQLi and how to insert data into database using PHP MySQLi.

Leave a Comment