Insert Query
Mysql Insert Query

To insert data

into MySQL table use mysql insert query.

Syntax 1:
insert into table_name(field1,field2,...fieldN) values(value1,value2,..valueN);

Syntax 2:
insert into table_name set field1=value1, field2=value2,  ….N;

Example 1:-
insert into tbl_feedback(name,email) values('Johan', 'test@gmail.com')

Example 2:-
insert into tbl_feedback set name='Johan', email='test@gmail.com'

Example 3:-
insert into tbl_feedback values('Johan', 'test@gmail.com')

Note :- if you insert all field then it is not necessary to declare all fields just like you can see above Example 3

Insert Data through PHP & Mysql

<?php
$server="localhost";
$username="root";
$password="";
$database="test";

$con=mysql_connect($server,$username,$password) or die("Mysql not connect");

$database=mysql_select_db($database,$con) or die("database not connect");

$query="insert into info set username='raviphpdeveloper',email='raviphpdeveloper@gmail.com'";
$result=mysql_query($query);

if($result)
echo"Record insert";
else
echo"Record not insert";

mysql_close($con)
?>

Insert Data through PHP & Mysqli (Procedural)

<?php
$server="localhost";
$username="root";
$password="";
$database="test";

$conn = mysqli_connect($server,$username,$password,$database);
if(!$conn){
die("MySQL Not Connected");
}

$query="insert into info set username='sunilseoexpert',email='sunilseoexpert@gmail.com'";
$result=mysqli_query($conn,$query);

if($result)
echo"Record insert";
else
echo"Record not insert";

mysqli_close($conn)
?>

Insert Data through PHP & Mysqli (Objected Oriented)

<?php
$server="localhost";
$username="root";
$password="";
$database="test";

$conn=new mysqli($server, $username, $password, $database);

if(!$conn) {
die("MySQL Not Connected");
}

$query="insert into info set username='prabhaphpdeveloper',email='prabhaphpdeveloper@gmail.com'";
$result=$conn->query($query);

if($result)
echo"Record insert";
else
echo"Record not insert";

$conn->close();
?>

Insert Data through PHP & Mysql (PDO)

<?php
$server="localhost";
$username="root";
$password="";
$database="test";

try {
$conn=new PDO("mysql:host=$server;dbname=$database", $username, $password);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query="insert into info set username='deepakphpdeveloper',email='deepakphpdeveloper@gmail.com'";

$conn->exec($query);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo  "MySQL Not Connected";
}

$conn=null;
?>


Previous
Next