Home » MySQL INSERT Query in PHP – MySQL
MySQL

MySQL INSERT Query in PHP – MySQL

Hello Friends, Are you looking for a MySQL INSERT Query in PHP – MySQL. This tutorial is only for you. Even more, I will explain how to implement INSET Query using PHP, MySQL and Command Prompt. Just keep reading the post and get the knowledge.

MySQL INSERT Query in PHP - MySQL

INSERT Query in MySQL Syntax

First of all, I will show you the main syntax of query. So, you can get basic ideas how query looks like and how to enter table name and values in query.

There are 3 methods to write INSERT Query in MySQL. You can use any method among these 3 and insert the value inside the database.

1) First Method

INSERT INTO table_name 
( column1, column2,...columnN )
VALUES
( value1, value2,...valueN );

2) Second Method

INSERT INTO table_name 
VALUES
( value1, value2,...valueN );

3) Third Method

INSERT INTO table_name 
SET
column1 = 'value1',
column2 = 'value2',
...

You can replace table_name with your table and same as column and values.

INSERT Query in PHP

You can refer below code and fire insert query in PHP. I have used the method no 3 for insert operation.


<?php 

$DB_Host = 'localhost';
$DB_Name = "database_name"
$DB_Username = 'database_username';
$DB_Password = 'database_password';
$con = mysql_connect($DB_Host,$DB_Username,$DB_Password) or die(mysql_errno());
$db = mysql_select_db("$DB_Name",$con) or die(mysql_error());
				
// INSERT Query
$qry = '
INSERT INTO admin_table
SET 
name = "John Patel",
email = "info@johnpatel.com"
';
$result = mysql_query($qry);

if(!result)
{
  die ('Error:: in insert'.mysql_error());
}
else
{
  echo "Data Inserted Successfully";
}

?>

First, you have to connect your database with some code which is written above the query. So, when your connection is proper with the database then you can implement the query.
This query will insert the name as John Patel and email as [email protected] in database table admin_table. If all goes well then the “Data Inserted Successfully” message appears.

MySQL INSERT using Command Prompt

Write the syntax below in command promp to fire MySQL INSERT. We will use SQL INSERT INTO command to insert values in admin_table.


root@host# mysql -u root -p password;
Enter password:*******
mysql> use DB_Name;
Database changed

mysql> INSERT INTO admin_table 
   ->(name, email, phone)
   ->VALUES
   ->("John Patel", "info@johnpatel.com", "+919909666700");
Query OK, 1 row affected (0.01 sec)
mysql>

NOTE: Please note arrow(->) signs are not required in SQL command. They are automatically created by CMD and it denotes the new line.

Finally, you can use above all methods and INSERT data in MySQL. I hope you will like this tutorial and it will help you in web development. Please share it if you like it.

Releated Articles: