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

How to Insert Data through PHP Code

 1. Connect with mysql connection

$con=mysql_connect("localhost","root","") or die("Mysql not connect");

2. Connect with database

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

3. Create mysql insert query and run it.

$query="insert into info set username='shishir012010'";
$result=mysql_query($query);

4. Check Record properly insert into database or not

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


Example 1:- PHP full script to store data into database

<?php

$con=mysql_connect("localhost","root","") or die("Mysql not connect");

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

$query="insert into info set username='shishir012010'";
$result=mysql_query($query);

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

?>

Example 2:- PHP Script to Insert data through form.

<?php
if(isset($_POST['Submit']))
{
$con=mysql_connect("localhost","root","") or die("mysql not connect");

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

$userid=$_POST['userid'];
$username=$_POST['username'];

$query="insert into info(userid,username) values('$userid','$username')";

$result=mysql_query($query);

if($result)
$msg="Record insert";
else
$msg="Record not insert";

}
?>
<html>
<head>
<title>Insert Data</title>
</head>
<body>
<form name="frm" action="" method="post">
<table width="296" border="1" align="center" cellpadding="0">
<tr>
<td colspan="2" align="center">Registraction form </td>
</tr>
<tr>
  <td colspan="2" align="center">
  <?php if(isset($msg)) echo $msg; ?>
  </td>
  </tr>
<tr>
<td width="107">User ID </td>
<td width="177">
<input name="userid" type="text" id="userid" /></td>
</tr>
<tr>
<td>User Name </td>
<td><input name="username" type="text" id="username" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<input type="submit" name="Submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>


Previous
Next