Home >>MySQL Tutorial >PHP MySQL Insert

PHP MySQL Insert


PHP MySQL Insert Query

The INSERT INTO statement is used to add new records to a database table. The insert statement is used to add new records to a database table. each time a new record is to be added we use INSERT INTO statement for that purpose. There are two ways of inserting records either explicitly providing the column name with values respectively or simply by providing values of table but doesn't specify the column name.

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

The second way doesn't specify the column names where the data will be inserted, only their values.

Syntax

	
INSERT INTO table_name VALUES (value1, value2, value3,...) 	

Ex In the previous chapter we created a table named "empInfo", with four columns; "emp_id", "name", "emailid" and "mobile". Use the same table to insert values inside empInfo table.

<?php
$con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error());
	  
//get data from html form
$name=$_GET['name'];
$eid=$_GET['eid'];
$mob=$_GET['mob'];
	  
//Insert values in empInfo table with column name 
$query="INSERT INTO empInfo(emp_id, name, email, mobile)  VALUES ('', '$name','$eid','$mob')";
mysqli_query($con,$query);
	
//OR		
//Insert values in empInfo table directly

$query="INSERT INTO empInfo VALUES ('', '$name','$eid','$mob')";
mysqli_query($con,$query);						
?>

HTML Form

<form>

Enter your name<input type="text" name="name"/><hr/>

Enter your email<input type="text" name="eid"/><hr/>

Enter your mobile<input type="text" name="mob"/><hr/>

<input type="submit" value="INSERT"/><hr/>

</form>

In the above example the values such as name , eid , mobile number are fetched from the form and inserted into empInfo table using INSERT INTO query.

Insert data from HTML form directly in database

<?php
$con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error());

//Insert values into empInfo table directly using form
$query="INSERT INTO empInfo VALUES ('', '{$_GET['name']}','{$_GET['eid']}','$_GET['mob']')";
mysqli_query($con,$query);						
?>

HTML Form

<form>
 
Enter your name<input type="text" name="name"/><hr/>

Enter your email<input type="text" name="eid"/><hr/>

Enter your mobile<input type="text" name="mob"/><hr/>

<input type="submit" value="INSERT"/><hr/>

</form>	

In the above example values such as name , eid , mobile number are fetched from the form and inserted into empInfo table without providing the column names


Popular Tutorials