create-html-form-to-insert-data-into-mysql-database-using-php-

This article explains data insertion in MySql using HTML Form. You must have seen contact/feedback Forms in many websites. These Forms are designed using standard HTML Form elements. On the back end, SQL queries are used to perform DML operation using information provided by user. Any server side scripting language can be used to insert data in database. Following steps explain this process using PHP and MySql.

1-     First of all create a table in MySql database using following command. This command can be executed in any MySql query browser like phpMyAdmin.

CREATE TABLE contact (
msg_id int(11) not null auto_increment,
name varchar(255) NOT NULL ,
email varchar(255),
msg varchar(2000) NOT NULL,
PRIMARY KEY (msg_id))
2-     Now open notepad, copy and paste following HTML and save your file as “contact.html”

<HTML>
<Head>
<title>Contact form</title>
<style type=”text/css”>
table{
border:1;
border-collapse:collapse;
font: normal 12px ‘Lucida Grande’,Verdana,sans-serif;
}
td{
color:#663333;font-family:verdana;
border-bottom: 1px solid #666;
padding-left:10px;
background-color:#F0F8FF;
}
#sub{ text-align:center;}
</style>
</Head>
<body>
<h2> FeedBack/Contact Form</h2>
<form action=”contact_insert.php” method=”POST” id=”insert”>
<table>
<tr>
<td >Name*</td>
<td  ><input type=”text” size=40 name=”name”></td>
</tr>
<tr>
<td >Email</td>
<td  ><input type=”text” size=40 name=”email”></td>
</tr>
<tr>
<td >Comments/Suggestions*</td>
<td  ><textarea  name=”msg” cols=40 rows=7></textarea> </td>
</tr>
<tr>
<td colspan=2 id=”sub”><input type=”submit” name=”submit” value=”submit” ></td>
</tr>
</Table>
</form>
</BODY>
</Html>
3-     Open a new notepad window and copy following PHP source code. Save the file as “contact_insert.php”.

<?php
// contact to database
$connect = mysql_connect(“localhost”, “root”, “pass”) or die (“Error , check your server connection.”);
mysql_select_db(“test”);

//Get data in local variable
$v_name=$_POST[‘name’];
$v_email=$_POST[’email’];
$v_msg=$_POST[‘msg’];

// check for null values
if ($v_name==””  or $v_msg==””)
echo “All fields must be entered, hit back button and re-enter information”;
else{
$query=”insert into contact(name,email,msg) values(‘$v_name’,’$v_email’,’$v_msg’)”;
mysql_query($query)  or die(mysql_error());
echo “Your message has been received”;
}

?>
4-     Now open “contact.html” in your web browser, fill the form and press submit button  as shown in the figure below
contact_a

When you press submit button, information in Form elements is passed to “contact_insert.php” file. This file checks the input for NULL values , inserts data in database and displays message as shown in figure below

contact_b

 

Comments are closed.