Php is a server side scripting language it allows to store data into database at server level. In this post I will illustrate you how insert data with Sql insert query in PHP.
insert into tablename(column1,column2,...) values(value1,'value2',...);
Note : Value1 is written without single quotes, because it is an integer value and value2 is a string.
For example : value1 = 1 and value2 = Albert.
First of all, I have created HTML form, in which method is set to post ,to hide values in URL which flows on form submission.
Next, I wrote PHP code where the main functionality of insertion of values into database is performed.
At MySql database I have created a database named “colleges” and table named “students” which consists of five fields viz. “student_id”, “student_name”, “student_email”, “student_contact”, “student_address”.
Here in the download code provided below there is file naming db.sql in which sql queries are written for creating database, creating table and different columns in it.
You just need to import it in your phpmyadmin it will create the required tables.
MY-SQL Code
CREATE DATABASE IF NOT EXISTS colleges;
CREATE TABLE students(
student_name varchar(255) NOT NULL,
student_email varchar(255) NOT NULL,
student_contact varchar(255) NOT NULL,
student_address varchar(255) NOT NULL
)
After that use relevant path to run the program, like for example :
localhost/insert.php
Now fill the form fields and submit it, data will be saved to MySql database and a notification will be delivered “Data Submitted successfully”.
Watch out the live demo or download the code to use it
HTML File – insert.php
- Consists of form div “form”.
<!DOCTYPE html>
<html>
<head>
<title>PHP insertion</title>
<link href="css/insert.css" rel="stylesheet">
</head>
<body>
<div class="maindiv">
<!--HTML Form -->
<div class="form_div">
<div class="title">
<h2>Insert Data In Database Using PHP.</h2>
</div>
<form action="insert.php" method="post">
<!-- Method can be set as POST for hiding values in URL-->
<h2>Form</h2>
<label>Name:</label>
<input class="input" name="name" type="text" value="">
<label>Email:</label>
<input class="input" name="email" type="text" value="">
<label>Contact:</label>
<input class="input" name="contact" type="text" value="">
<label>Address:</label>
<textarea cols="25" name="address" rows="5"></textarea><br>
<input class="submit" name="submit" type="submit" value="Insert">
</form>
</div>
</div>
</body>
</html>
PHP Code segment
- Insert form information into database.
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server
$db = mysql_select_db("colleges", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$address = $_POST['address'];
if($name !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("insert into students(student_name, student_email, student_contact, student_address) values ('$name', '$email', '$contact', '$address')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
?>
Css File – insert.css
- Includes basic styling of HTML elements.
@import "http://fonts.googleapis.com/css?family=Droid+Serif";
/* The Above Line Is To Import Google Font Style */
.maindiv {
margin:30px auto;
width:980px;
height:500px;
background:#fff;
padding-top:20px;
font-family:'Droid Serif',serif;
font-size:14px
}
.title {
width:500px;
height:70px;
text-shadow:2px 2px 2px #cfcfcf;
font-size:16px;
text-align:center
}
.form_div {
width:70%;
float:left
}
form {
width:300px;
border:1px dashed #aaa;
padding:10px 30px 40px;
margin-left:70px;
background-color:#f0f8ff
}
form h2 {
text-align:center;
text-shadow:2px 2px 2px #cfcfcf
}
textarea {
width:100%;
height:60px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:7px;
border:none
}
.input {
width:100%;
height:30px;
border-radius:2px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:7px;
border:none;
margin-bottom:20px
}
.submit {
color:#fff;
border-radius:3px;
background:#1F8DD6;
padding:5px;
margin-top:40px;
border:none;
width:100%;
height:30px;
box-shadow:0 0 1px 2px #123456;
font-size:18px
}
p {
color:red;
text-align:center
}
span {
text-align:center;
color:green
}
Conclusion:
I hope this tutorial helped you to insert data into database. If you want to share your feedback, you can easily do it via space provided below.
45 Replies to “Insert Data in Database Using PHP”
Many thanks to you. This article helps me a lot. I’ve been searching the answer for my php problem and found this usefull article. Sorry for my bad english, thanks again. keep up the good work!!! God bless…
Thanks for your appreciation …….!
Keep reading our other blog posts.
Check this for video tutorial
https://youtu.be/PMQPltmxJhM
Can any one tell me what is wrong with my codes because is given error message undefined index first at line 16
Have you done any changes in the code ? As at my end it is working fine, you just need to download the code , extract the file in your local server file , go to your Phpmyadmin import db.sql file and then open the program , using syntax : localhost/insert.php
Hope that will work for you.
Regards,
FormGet Team.
Wonderful
Hello Ambrose,
Hope that above tutorial had helped you , thanks for reading the post.
Regards,
FormGet Team
This is great. I was searching a good tutorial for days,this found and this is very simple…thank you very much! Please keep up the good and simple tutorials for beginners like us,thanks again.
Hello Kelum,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here
Regards,
FormGet Team
many thanks to its realy very helpful
Hello Ishaq,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here
Regards,
FormGet Team
i read Ur code, the code below its look the same as yours the problem is doesn’t work at all it’s give error when am try to insert into database
my code:
insert.php
Write your ACADEMIC COMMENT here
Write your SPORTS COMMENT here
Write your HOSTEL COMMENT here
Write OTHER INFOMATION you have here
php code to insert into database
<?php
if(isset($_POST['submit'])){
$message = $_POST['message'];
$message1 = $_POST['message1'];
$message2 = $_POST['message2'];
$message3 = $_POST['message3'];
if(empty($message)||empty($message1)||empty($message2)||empty($message3)){
$report = mysql_query("INSERT INTO civebox(sms_id, AcademicSms ,SportsSms ,HostelSms, OtherInfo)
VALUES ('$message','$message1','$message2','$message3')");
echo " message successfully sent ";
}else
{ echo " error in your query ";}
}
Hello Joseph,
First you check for the above given code , then change it according to you.
In your code you are lacking with database connections and all.
Hope that will work for you.
Regards,
Formget Team.
This is a good website…….
Hi.. Thanks you for the Post… helped a lot…. But i need help with my code….
I have two database tables Contact_info and Staff_Details. Now I have a foreign Key to the ContactID of the Contact_Info table from the Staff_details table and while entering the data from the form I want both the table to get the data .. How do I do that. Kindly advise.
fantastic… have been trying since a month and you gave the right code… wow.. yess.. thanks
this is realy great tutorial for every biggners …thanks for sharing this ……
It’s realy usefull.
wonderful!!!
thx
Thanks…………
Sir its good but i need insertion to using classes which show MVC Model .Thanks
Hello Anwar,
Thanks for your appreciation …….!
For insertion data via MVC Model see
https://www.formget.com/insert-data-into-database-using-codeigniter/
Hope that will work for you.
Regards,
Formget Team.
I want to insert form data to MySQL db when i click submit button.datas are not inserted,
this is my following code:
<?php
$conn = mysql_connect("localhost", "root", "");
if(!$conn)
{
die('could not connect:'.mysql_error());
}
$db = mysql_select_db("student");
or die ("unable to select to the database");
if(isset($_POST['submit']))
{
$name = $_POST['Name'];
$age = $_POST['Age_txt'];
$fathne = $_POST['Father_txt'];
$national = $_POST['nation_txt'];
$email = $_POST['Email'];
$mob= $_POST['mob_txt'];
}
if('$name'!=null) ||('$age'!=null)||('$fathne'!=null) ||('$national'!=null)||('$email'!=null)||('$mob'!=null){
$query = mysql_query("INSERT INTO stud(student_name,student_age,student_father,student_nation,student_email,student_mob) values ('$name', '$age', '$fathne', '$national','$email','$mob')");
}
else
{
echo("unable to insert the data”);
}
$result = mysql_query($query,$conn);
if($result)
{
echo(“Input data is succeed”);
} else
{
echo(“Input data is fail”);
}
?>
Thanks for the scripts @ admin.
But, please is the code strong enough to prevent hackers from bringing down my site?
Please check this article, We have write it especially for the security purpose.
https://www.formget.com/sql-injection-prevention-in-php-with-mysqli/
good work keep on
hi..im getting this error :Parse error: syntax error, unexpected ‘password’ (T_STRING), expecting ‘]’ in C:\xampp\htdocs\tutorialApi\form.php on line 11
i have this in my line 11 $password= [‘password’];
If i add password and username field ,then will it store the similar data in mysql Server??? Or if i create registration page, will it store data in mysql server? And keep increasing as per user register on it???
Hi Tushar,
If you want to add some additional field(username and password), then first you will have to make columns for these fields in the database table. Then, fetch the submitted values and insert the submitted values in the database table by adding the values and column name in the mysql query.
i want a dynamic form whose values gets added to the database can you please help me on that its quite urgent
I have where user can add many field as he want now i want store that form in database any help on it plz
its useful
I am using PHPStorm 8.0.3 C
,Codeigniter 3.0.3 and Wamp Server2.1ex32.
My OS is 32 bit with Windows 7 Ultimate and Processor:Intel(R)Core(TM)i3-2100 CPU
I have done with the above codes and all files…localhost/insert.php is displaying the same result as in the image above provided.But the problem I am facing is that my database is not inserted in MySQL database…The web page localhost/insert.php is accepting all the values but its not displaying it into the database due to the issue that my db.sql says that
No data resources are configured to run this SQL and provide advanced configuration.
SQL dialect is not configured.
Please tell me how to proceed.This code is very useful for me…Please resolve my issue….
the values entered in form inserts data into database everytime on refresh
Hey, I used this code and it was successful. Many thanks! Can you pls tell me how to insert data into two tables from one form?
For example, user registration form’s email and password should store in login table while other details are stored in user table.
Awesome
Thanks for this post…
i have problem w/ my add_process form at always say that i successfully added some data to my data base .. when i check my database table the data that i added was not found what maybe the wrong in my code
…
<?php
if(isset($_POST['submit'])){
$first=trim($_POST['fname']);
$last=trim($_POST['lname']);
$middle=trim($_POST['mname']);
$address=trim($_POST['address']);
$sex=trim($_POST['sex']);
$bday=trim($_POST['bday']);
$age=trim($_POST['age']);
if($first !=''||$last !=''){
$query = mysql_query("INSERT INTO secretary(f_name,l_name,m_name,address,sex,birthdate,age)VALUES
('$first','$last','$middle',$address','$sex',$bday','$age')");
echo "alert(‘Sucessfully added!’)”;
echo “window.open(‘index.php’,’_self’)”;
}
else{
echo “Insertion Failed Some Fields are Blank….!!”;
}
}
mysql_close($con); // Closing Connection with Server
?>
Many thanks to you.
This is great. I was searching a good tutorial for days,this found and this is very simple…thank you very much……
Hello sir can you pls tell me how to get table in php
Thanks a lot , it is working fine , but how to you add info to database
This code is inserting only first record into database.not every time ?can you suggest what to add in this code.
Your code works for MS SQL server too, I have this code which it works:
$tsql = “INSERT INTO SCORES (ID, Supervisor, ACCT, QARDate, COMMENTS) VALUES (?,?,?,?,?)”;
$parameters = array($_POST[ID], $_POST[Supervisor], $_POST[ACCT], $_POST[QARDate], $_POST[COMMENTS]);
$stmt = sqlsrv_query($connection, $tsql, $parameters);
My problem is QARDate is a datetime data type, and comments is varchar(MAX) in the database. How can I define those two fields in my html code? Do I need to change something in my PHP code to write to the table? How about date validation?
i want to submit form by inserting data in multiple table using one query.
please, can any one help me.
this is my code:
<?php
require "common/session.php";
if(isset($_POST['next']))
{
$con = mysqli_connect('127.0.0.1', 'root', '');
if ($con)
{
echo 'Connection works fine’;
}
if (mysqli_select_db($con, ‘pulse’))
{
echo ‘database selected ‘;
}
$csType = $_POST[‘csType’];
$clubForm = $_POST[‘clubForm’];
$nameEN = $_POST[‘nameEN’];
$nameAR = $_POST[‘nameAR’];
$descriptionEN = $_POST[‘descriptionEN’];
$descriptionAR = $_POST[‘descriptionAR’];
$subDuration = $_POST[‘subDuration’];
$logo = $_POST[‘logo’];
$phoneNumber = $_POST[‘phoneNumber’];
$telNumber = $_POST[‘telNumber’];
$email = $_POST[’email’];
$facebook = $_POST[‘facebook’];
$twitter = $_POST[‘twitter’];
$instagram = $_POST[‘instagram’];
$youtube = $_POST[‘youtube’];
//$website = $_POST[‘website-link’];
$specialties_nameEN = implode(‘,’, $_POST[‘clubox’]);
//$specialties_nameEN = $_POST[‘clubox[]’];
$specialties_nameAR = $_POST[‘nameAR’];
$facilities_nameEN = implode(‘,’, $_POST[‘clubox’]);
//$facilities_nameEN = $_POST[‘nameEN’];
$facilities_nameAR = $_POST[‘nameAR’];
$categories_nameEN = implode(‘,’, $_POST[‘clubox’]);
//$categories_nameEN = $_POST[‘nameEN’];
$categories_nameAR = $_POST[‘nameAR’];
$timing = $_POST[‘timing’];
$phoneNumber2 = $_POST[‘phoneNumber’];
$gender = $_POST[‘gender’];
$sql1 = “INSERT INTO clubstore (csType, clubForm, nameEN, nameAR, descriptionEN, descriptionAR, subDuration, logo, phoneNumber, telNumber, email, facebook, twitter, instagram, youtube) VALUES(‘$csType’, ‘$clubForm’, ‘$nameEN’,’$nameAR’, ‘$descriptionEN’, ‘$descriptionAR’, ‘$subDuration’, ‘$logo’, ‘$phoneNumber’, ‘$telNumber’, ‘$email’, ‘$facebook’, ‘$twitter’, ‘$instagram’, ‘$youtube’)”;
$sql2 = “INSERT INTO ‘specialties’ (‘nameEN’, ‘nameAR’) VALUES(‘$specialties_nameEN’, ‘$specialties_nameAR’)”;
$sql3 = “INSERT INTO facilities (‘nameEN’, ‘nameAR’) VALUES(‘$facilities_nameEN’, ‘$facilities_nameAR’) “;
$sql4 = “INSERT INTO categories (nameEN, nameAR) VALUES(‘$categories_nameEN’, ‘$categories_nameAR’)”;
$sql5 = “INSERT INTO locations (timing, phoneNumber, gender) VALUES(‘$timing’, ‘$phoneNumber2’, ‘$gender’)”;
function addFunction($sql1, $sql2, $sql3, $sql4, $sql5) {
$sql = $sql1 + $sql2 + $sql3 + $sql4 + $sql5;
if (mysqli_query($con, $sql))
{
//$_SESSION[‘username’]= $firstName.” “.$lastName;
header (“refresh:1; url=info.php”);
}
else
{
mysqli_query($con,$sql) or die(mysqli_error($con));
$_SESSION[‘username’]= “”;
$errorToShow=”there is something wrong”;
}
}
}
?>
SIR,
it is humble request you to please solve my problem.
It is showing an error. error is “Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /opt/lampp/htdocs/insert.php:34 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/insert.php on line 34” . I am facing this problem from long time.
please give me a solution.
thank you formget team…. It is useful