In this tutorial you will learn how to insert records in a table using MYSQLi query .
Let’s start to create a INSERT INTO statement with values using MYSQLi Procedural and MYSQLi Object-oriented method.
Here we are going to insert a record into user table by specifying coloum fields like: '
user_id', 'first_name', 'last_name', 'email', 'phone'
.
Here '
user_id'
is an AUTO_INCREMENT PRIMARY KEY coloum.
Example: MYSQLi Query
MYSQLi Procedural Method
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php // create database connection $host="localhost"; $username="root"; $password=""; $database="test"; $con=mysqli_connect($host,$username,$password,$database); //test connection if($con!=true){ die("Database connection error:".mysqli_connect_error()); } $sql="INSERT INTO user (first_name,last_name,email,phone) VALUES ('Robert','Hanery','robert@mail.com',9999999999)"; $result=mysqli_query($con,$sql); if($result){ echo "New Record Inserted Successfully"; }else{ echo "Error, Record not inserted."; } mysqli_close($con); ?> |
MYSQLi Object-oriented Method
MySQLi Object-oriented method is more faster and secure than MYSQLi Procedural method. That’s the reason we prefer to use MYSQLi Object-oriented method in php.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php // create database connection $host="localhost"; $username="root"; $password=""; $database="test"; $con=new mysqli($host,$username,$password,$database); //test connection if($con->connect_error){ die("Database connection error:".$con->connect_error); } $sql="INSERT INTO user (first_name,last_name,email,phone) VALUES ('Robert','Hanery','robert@mail.com',9999999999)"; $result=$con->query($sql); if($result){ echo "New Record Inserted Successfully"; }else{ echo "Error, Record not inserted."; } $con->close(); ?> |
trong>
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co