Complete Computer Knowledge Portal

Monday, December 9, 2013

How to insert PHP Form data into MYSQL Database?

Here are some easy steps that are used to insert PHP data into MYSQL database
      1) Create MYSQL database
           2) Create index.php or index.html page with required inputs.
           3) PHP script to insert data.
           4) Database connection
Create the database testing
CREATE DATABASE `testing`;
 
Create Table info on testing Database:
Table info is created with three fields: id, name and Email Address. Id will be automatically incremented after every insert operation.
CREATE TABLE `testing`.`info` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 100 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM

Create form to insert data (index.php)
This form will accept two fields: Name and E-mail Address. These fields can be more or less depending upon user requirements.
<?
<form method="POST" action="submit.php">
< p> Name:<input type="text" name="T1" size="20"></p>
  <p>E-Mail<input type="text" name="T2" size="20"></p>
  <p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
?>

Database Connection (db_connection.php)
This script is used to define hostname, MYSQL database name, User name for this Database, Database Password.
<?php
$host="localhost";
$username="your_db_username";
$password="your_db_password";
$db_name="testing";
$con=mysql_connect("$host","$username","$password") or die("could not connect");
$db=mysql_select_db("$db_name")or die("cannot select DB");
?>

PHP script to insert data: (submit.php)
In this script variable $name will contains the name to be inserted and variable $email will contain email ID to be inserted.
<?
Include(“db_connection.php”);
$name=$_POST[‘T1’];
$mail=$_POST[‘T2’];
$sql=”INSERT INTO info(name,email) VALUES (‘$name’,’$email’)”;       
$result=mysql_query($sql);
if($result)
{
?>
<script language="javascript" type="text/javascript">
alert("Record Added Successfully");
windows.location="add_vendor.php";
</script>
<?php
}
else
{
echo"Error";
}}
?>

No comments:

Post a Comment