How To Insert Data Into Mysql Db Using Form In Php Database Enter Code

Forums » MySQL » How To Insert Data Into Mysql Db Using Form In Php Database Enter Code
this page will show you exactly step by step on how to insert data in your mysql database using php script very simple you can test for yourself and very easy to follow and many positive comments from visitors
ok, when i started to learn about php, i wanted to know how i can put that data from a HTML form into mysql database. it wasn't easy to lear because there was so much stuff i need to know. so to help you, make sure you have these things so you will be able to learn my tutorial here on how to insert data into mysql from a PHP web form.

1. Knowledge of HTML (average knowledge)
2. Knowldege of PHP (average knowledge)
3. Knowledge of Mysql (average knowledge)
4. Have a website with PHP (if you don't have a PHP/mysql website, visit our friends at www.webune.com and signup for a PHP/mysql web hosting plan)


now that you have at least all the four points above, its time to show you how you can insert the data.



Step 1



ok, i will give you a short tutorial...

In this example, lets say i want to collect data from a user. For the purpose of this tutorial guide, i only need the user's name and their email address. so i only need two text fields. one is user_name and the second one is user_email. so this is how the form would look like in HTML:

this is how the form will look like:



Name:

Email:







FORM HTMLCODE
<form method="post" action="">
Name:<br>
<input type="text" name="user_name">
<br>
Email: <br>
<input type="text" name="user_email">
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>





STEP 2



the next step would be to have php check if the form has been submited or not. if the form has been submitted..

the way you can tell if a form has been submitted is to check if our submit button has a value.. if you look closely in our form html. i have this

HTML CODE
<input type="submit" name="Submit" value="Submit">


as you can see, the name of the submit button is called "Submit" so that the string variable name we can find out if its true or false. to check if the form is submitted i will use the if else operator in php

PHP CODE
if (isset($_REQUEST['Submit'])) {
// INSERT DATA FROM FORM ONCE THE FORM HAS BEEN SUBMITTED
} else {
// DISPLAY FORM IF FORM HAS NOT BEEN SUBMITTED
}





Step 3



ok, on step three, you will need to have the following information, if you dont have this information,,, you will not be able to continue on with this tutorial

  1. hostname (usually localhost)
  2. database user name (if you don't have this contact your host company)
  3. database user password (if you don't have this contact your host company)
  4. database name (if you don't have this contact your host company)
  5. database table name (you create this. you can create a table in phpmyadmin)


if you dont have all these requirements contact you webhosting company.

if you are a Webune customer, contact us and we will be glad to provide this information for you.




Step 4



the next step involves in us creating some tables in the mysql database.

so login to your database using phpmyadmin. if you are a webune customer, login to the control panel and click on the phpmyadmin link, you will need to login to the database in step 3.

once you are in phpmyadmin click on the SQL tab and copy and past this sql dump into the text area:

CREATE TABLE `user_info` (
`user_name` VARCHAR( 50 ) NOT NULL ,
`user_email` VARCHAR( 50 ) NOT NULL
);


this will create a table called user_info in your database, this is where we will enter the information from the form. as you can see, we created two fields, one called user_name and the other one called user_email



its should look something like this on your phpmyadmin
phpmyadmin snapshot




now its time to put the whole thing together.. we wrote up this simple script to show you how you can add. we made this script simple so that you can hack it, modify it or do whatever you want with it so you can practice and how how it all works. one this we ask is that please dont remove the www.webune.com link - we would appreciate it if you dont.

so open your favorite text editor. if you have windows like i do, im using windows xp, open a blank notepad and copy and paste the following php code into it:

webune.php
<?php
####################################################################
# THIS SCRIPT CREATED BY WWW.WEBUNE.COM
# PLEASE DONT ERASE THIS
###################################################################
####################################################################
################ DATABASE CONFIGURE ##############################
####################################################################
$hostname = "localhost"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost
$db_user = "username"; // change to your database password
$db_password = "passwd"; // change to your database password
$database = "databse"; // provide your database name
$db_table = "user_info"; // leave this as is


# STOP HERE
####################################################################
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
?>
<html>
<head>
<title>How To Insert Data Into MySQL db using form in php</title>
</head>
<body>

<?php
if (isset($_REQUEST['Submit'])) {
# THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE
$sql = "INSERT INTO $db_table(user_name,user_email) values ('".mysql_real_escape_string(stripslashes($_REQUEST['user_name']))."','".mysql_real_escape_string(stripslashes($_REQUEST['user_email']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into our database<br><br><img src="http://www.webune.com/images/headers/default_logo.jpg"';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>How To Insert Data Into MySQL db using form in php</h1>By <a href="http://www.webune.com">Webune.com</a><hr>
<form method="post" action="">
Name:<br>
<input type="text" name="user_name">
<br>
Email: <br>
<input type="text" name="user_email">
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
</body>
</html>



Now make sure to change the mysql connections settings. so for example, i have these settings. NOTE: this are fake, so make sure to change them, otherwise, this script will error out because it cant connect to the database.

$hostname = "localhost";
$db_user = "webune_user";
$db_password = "mypassword";
$database = "database";
$db_table = "user_info";

as you can see on my example, my hostname is localhost
my database username is webune_user
the password for my database is mypassword my database is database
and my database table is user_info

so now that you have changed these setting to your database credentials, save the notepad file as webune.php

now upload to your php website and open it with your browser, enter the information and once you get a sucess message, the information was entered into the datase.



i tested and it works. if you are a webune customer, you should not have any problems, since this test is done on our servers

here is how the form looks like in my firefox browser when i open webune.php
webune-php

and when i submit the form with my name and email address i get this
mysql-form-submitted

now when i go to my phpmyadmin, i can confirm that the information i've entered on the form, was inserted into my database
phpmyadmin-insert.jpg

NOTE: you should not by any means deploy this code in a real production website, as there are many security issues, like sql injection. the purpose of this tutorial is to give you an idea on how the process of getting information from your users and storing it in a database so you can later diplay it or use it with your web applications. if you are not sure what i mean by slq injection, you can find lots of resources on this website or google it and you will find. for example you can google this string:

How To Avoid And Prevent Sql Injection mysql_real_escape_string wallpaperama


done..

i hope this helps you

remember if you need php web hosting

webune has the right service for you

UPDATE:::
today we created a video following these steps and how it works for beginners:



UPDATE 2-19-2012 = I know some of you have criticize me because my grammar is not so good. I must apologize, English is my second language, but i am trying very hard to share what i know with everyone from around the world and English and Spanish are the most spoken languages spoken in the free world. so i wrote this tutorial in Spanish and in English. I am from the country of El Salvador. Our national language is Spanish, so i hope you understand. :)
waqas
18-868-211452-100001684073576-1996714-n.jpg
hey guyz here iz a better solution of this problem plz visit my personal site waq
cycler
Did you run a grammar/spell checker on this article? I know they had them back in 2007. :-) Sentences start with a capital letter and I is capitalized. If you are not sure how to spell a word, look it up. Poor grammar and spelling does not help a good article.
waqas
by defaultits not mandotry.bt u can make a check tht its mandtry to fill allthe feilds
Prachir
Thanks a lot of for that,,,,,,,,,,
waqasuow.hostzi.com/proje
bro replace all the duble qoutes wth single qouts. hope so it will work proprly
Malik
Hi Friends! check this link hopefully this will helpful for you. develope This is a step by step example.
Jeff
Thank you so much for your tutorial. I am new with PHP and I've learned a lot with your tutorial. Pleas help me a to do with a simple membership system with this field: Name, Age, Address and Salary system using PHP with HTML form and my sql. Thanks...please send me code with my email: jeffclaud18 - at - yah
website
Nice video uso
Jeff
Thank you so much for this page - It's got me out of the manureI got myself into. When I found this lot I started all over again and just forgot about the mess I made yesterday. Still struggling with the updating a database with a web form though
Sathish
Nice explanation.
fred
i am not able to insert the values this is my code, please go through and reply me...... <?ph $hostname = "localhost"; $ = ""; $db_passwo = ""; $database = "hyundaicms"; = "cars"; $db = mysql_connect($ $db_user, $db_password); $db); ?> <html values into cars table</title> < <?php if(is THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE $sql = "INSERT INTO $db_table(car_i values ('','".mysql_re '".mysql_real_e '".mysql_real_e '".mysql_real_e '".mysql_real_e '".mysql_real_e = mysql_query($sq ,$db)) { echo '<h1>Thank you</h1>Your information has been entered into our database<br><br src="www else { echo "ERROR: ".mysql_error() else { ?> <form action="" method="post"> <p>Car Model:<input type="text" name="carmodel" <p>Car Price:<input type="text" name="carprice" <p>Car Color:<input type="text" name="carcolor" <p>Car Image:<input type="text" name="carimage" <p>Year of Manufacture:<in type="text" name="manufactu <p>Car Specification:< </p><textarea cols="60" rows="10" name="specifica car specifications here, please</textare <p><input type="button" name="submit" value="Submit"> <input type="reset" value="Reset the form"></p> </form> <?php } ?> </body> </
waqas
06-868-211452-100001684073576-1996714-n.jpg
here iz a very easy and more efficient guide for u guyz plz visit w-a-q-a-s-u-o-w remove all the (-) from ths URL nd opn it.thnx
santu
Hi... how to enter the details from table present in form of html into mysql database. Here I used editable table format in form of html , where i can enter the values, after entering I want to store those values into database. pls help me along with sample code
jvkirankumar
31-868-download.jpg
very good explanation i inspired . keep going man!
Thushande
my code is this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//E "w3. xmlns="w http-equiv="Con content="text/h charset=iso-885 /> <title>confi page</title> </ = "localhost"; $db_user = "sroot"; $db_password = "200914066"; $database = "student_db"; $db_table = "registration"; = mysql_connect(" "200914066"); m = "INSERT INTO $db_table(fulln VALUES ('".mysql_real_ = mysql_query($sq '<center><h1>Th You</h1>Your information has been entered into our database<br><br src="img10.jpg" "ERROR:".mysql_ <table width="816" border="0" align="center" cellpadding="10 cellspacing="0" <tr> <td height="2" colspan="2" align="center" bgcolor="#99663 size=" 3" color="#FFFFFF" <p><strong>Mili Institute of Science and Technology</str <p>&nbsp;</p></ </tr> <tr> <td height="93" colspan="2" align="center" bgcolor="#99663 src="img6.png" width="422" height="272" alt="" /></td> </tr> <tr> <td height="198" colspan="2" align="center" bgcolor="#FFFF9 size=" 3" color="#000099" Ragistration Form...</p> <p><img src="img9.jpg" width="417" height="112" alt="" /></p> <p>&nbsp;</p></ </tr> <tr> <td colspan="2" bgcolor="#B9AD9 width="500" border="0" align="center" cellpadding="5" cellspacing="10 <tr> <td width="140" bgcolor="#CCCC0 Name:</td><td width="400"> < name="form1" method="post" action="config. <input type="text" name="fullname" maxlength="255" </form></td> </tr> <tr> <td bgcolor="#CCCC0 Type:</td> <td width="400"><fo name="form2" method="post" action="config. <FORM ACTION="config. method="post" onSubmit="retur dropdown(this.d NAME="ddm1"> <O VALUE="">Select your user type from below... <OPTION VALUE="/" >Student <OPTIO VALUE="/" >Course cordinator <OPT VALUE="/" >Head of Department <OPT VALUE="/tags/" >Account Officer <OPTION VALUE="/" >Dean <OPTION VALUE="/" >Exam Controller </SE </tr> <tr> <td bgcolor="#CCCC0 address:</td> <td width="400"><fo name="form3" method="post" action="config. <input type="text" name="email" maxlength="100" </form></td> <td>&nbsp;</td> </tr> <tr> <td bgcolor="#CCCC0 ID:</td> <td width="400"><fo name="form4" method="post" action="config. <input type="int" name="userid" maxlength="9"> </form></td> <td>&nbsp;</td> </tr> <tr> <td bgcolor="#CCCC0 Password:</td> <td width="400"><fo name="form5" method="post" action="config. <input type="text" name="userpassw maxlength="50"> </form></td> <td>&nbsp;</td> </tr> <tr> <td bgcolor="#CCCC0 password:</td> <td width="400"><fo name="form6" method="post" action="config. <input type="text" name="retypeuse maxlength="50"> </form></td> <td>&nbsp;</td> </tr> </table> name="form7" method="post" action="config. <input type="submit" name="Submit" value="Submit" align="absmiddl </form></center </p> <p>&nbsp;< am getting massage that data has been stored in data base, but table also properly created, there is no data in data base.Please help me on this issue.
THushan
sir it is very important tutorial with very simple English and this should be the way to teach. I have take this as a guide line for my coding...I got the massage as Thank you ur information has stored. but given info(inputs)are not physically seen in data base. what should I do sir.Thank u very much sir...
vamika
m unable 2 run it.... showing an error..
hayden
this was really awesome.
Mohammed
trust me it was vevry very helpful.....eve is so precise and clear....u dont even need to repeat 1 line....very nice....
Abeera
hi, thanks for it. But I wanted to insert data into my sql data base. To put that at ysapak dot com and madina786.c Now I will be trying the way you said. Thanks again
Rafi
You are welcome dear....
Pradip
Thank you...
Narayan
thank you this page is very helful to insert data in dATABSE USING PHP FORM THANK YOU SO MUCH
anvesh
IT IS AWESOME.
bari
no checks,..it accept blank values as well
kalaiselvi
thanks you so much this is really usefull... it`s working
aakku
but how can i edit my table after someone has submitted the form??
Tito
Hi, great stuff !!! thanks for sharing with us. It's help me lot and this link mindstick dot com / help me lot !!!! thanks !!!!!
Someone
I can't believe it, I've been searching all the day for a proper tutorial to help me insert into a database I've made, till I got to this.. BEST TUTORIAL EVER!
Farai
I have a table in mysql database that has 18 fields I have managed to populate other tables without any problem but this table is not could it be that the fields are too many the code is below:

<?php
$con = mysql_connect('localhost' (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db('hel $con);

$sql = "INSERT INTO call (Call_Number, Date_Logged, Time_Logged, Date_Cleared, Time_Cleared, User, Logged_By, Category, Problem, Cause, Solution, Cleared, Cleared_By, Clear_Method, Clear_Time, Comments, Days, Call_Age)
VALUES ($_POST[call_num],'$_POST $_POST[call_num] "---" $_POST[call_date_logged] "---" $_POST[call_time_logged]; $sql;
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Record successfully added";

mysql_close($c
Saurabh
WOW, its working great! :D
SwatI
I have written this code But not working;;;;;;
<?php
mys */
$sql="INSERT INTO emp (id,name,salary,desig) values ('','$_REQUEST['na']','$_
if($result = mysql_query($sql ,$db))
{
echo '<h1>Thank you</h1>Your information has been entered into our database<br>';
}
el
{
echo "ERROR: ".mysql_error();
}
}
?>
And always I gt this result on my browser----->
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\xampp\htdocs\HomePract on line 12

Can U help me about it..Tarus

SwatI
Tarus
29-868-tarus.jpg
This is a great page, everything worked perfectly. How about the code for retrieving data from mysql database? Thanks once gain, it made my day.
Ganiu
i really love this short tutorial. can u please share with us how to create a form that will go with image into a database?
THANK
This was so much help, it helped me create a Order Status script where an admin on our website can update the status of a customers order, then the customer will see the status when they login there account. Thanks again it helped alot!
Asiimwe
19-868-xara.jpg
Lots of Thanks to the guy who designed this stuff....it sure does work
sunil
please send me how to insert data into database from form in php?
suchait
thnx for help......
Rob
You must run it from a PHP server, you can not run it off your local computer, must be on a hosting server that supports PHP or an apache server
Nishant
17-868-here-i-am.jpg
can anybody tell me how to display uploaded data in SQL on HTML.
Nicky
I want a code to help me insert into the database from the PHP form. Help the form is emptied but nothing goes into the database.
Lavender
Thanks so much ,it was helpful but i got this error
Warning: mysql_query() expects parameter 2 to be resource, null given in C:\xampplite\htdocs\kasys on line 22
ERROR:
BVK
Thanks a lot friend.. i was really got stuck in this concept n your code helped me to come out of it..
Kelly
Oh wonderful tutorial!!! It’s help me a lot.
Also "php-exampl " helps me to learn PHP, MySQL & CakePHP with ready made code examples.

Kelly
Web Developer, University of Technology, Sydney, Australia
waseem
thanks buddy....
alpesh
thanks.... pls sent update,delete me,
Vik
simple delivery but effective, I have all the other stuff (server, phpmydmin, mysql etc)prepared earlier, Now I find your tutorial to be a great help to put it all the pieces together. thank you
Noah
this tutorial was really helpful. i had been looking for a way around submitting forms into my database for a while but couldnt get a suitable means until i came across this site... u are the bomb... thankx...
Nikunj
I got follwing error messege when tried to insert :

ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from) values ('ngadsfs','fdasd')' at line 1 :

sammit
it is very interesting!
you make me feel cool.I solve the problems I had with mysql
Title: How To Insert Data Into Mysql Db Using Form In Php Database Enter Code [870]
Tags: mysql help database tutorial teach learn