We can insert data into MySQL tables by executing SQL INSERT statement through PHP function mysql_query.This tutorial will show you how to insert data into mysql database.
Here i will create 3 php files and a Table under a Database:
- connect.php // Database configuration file
- insert.php // Contains PHP and HTML code
- db.php // insertion code will run here
- "insertion" table in database "test" .
Create Mysql Database "test" and create table "insertion".
CREATE TABLE `test`.`insertion` ( `fname` VARCHAR( 50 ) NOT NULL , `lname` VARCHAR( 50 ) NOT NULL , `emailid` VARCHAR( 50 ) NOT NULL ) ENGINE = MYISAM ;
Step 2 .
Create Database configuration file : connect.php and write the bellow code.
<?php $con=mysql_connect("localhost","root",""); if(!$con) { die("Connection not Open".mysql_error()); } mysql_Select_db("test",$con); ?>
Step 3 .
Create insert.php and write the bellow code.
<html> <head><title>Form</title></head> <body> <table width="300" border="0" align="center"> <tr> <td><form name="form1" method="post" action="db.php"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td colspan="3"><strong>Insert Data Into MySQL Database </strong></td> </tr> <tr> <td width="71">Name</td> <td width="6">:</td> <td width="301"><input name="fname" type="text"></td> </tr> <tr> <td>Lastname</td> <td>:</td> <td><input name="lname" type="text"></td> </tr> <tr> <td>Email</td> <td>:</td> <td><input name="email" type="email"></td> </tr> <tr> <td colspan="3" align="center"> <input type="submit" name="Submit" value="Submit"> </td> </tr> </table> </form> </td> </tr> </table> </body> </html>
Step 4 .
Create Database insertion File : insertdb.php and write the bellow code.
<?php include("connect.php"); if(isset($_POST["Submit"])) { $i=mysql_query("insert into insertion (fname,lname,emailid)values ('".$_POST["fname"]."','".$_POST["lname"]."','".$_POST["email"]."')"); if($i<0) { echo "Not Inserted"; } else { echo "Successfully Inserted"; } } ?>
1 comments so far
don't use mysql_* functions anymore, these are no longer safe ...