Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / PHP Tutorial / PHP Advance / PHP MySQL Insert Into Database Without Refreshing Page

PHP MySQL Insert Into Database Without Refreshing Page

April 28, 2015 by Belal Khan 30 Comments

Hello friends, in this PHP MySQL Insert into Database tutorial we will use jQuery AJAX method to insert values in our MySQL database without refreshing our web page. So lets begin.

PHP MySQL with AJAX Tutorial

  • You can read this tutorial or you can watch this playlist for complete detailed explanation.

What you need before starting with PHP MySQL Insert Tutorial?

  • WAMP / XAMPP server (I will be using wamp)
  • Notepad++ (notepad is also ok)
  • Little knowledge of PHP, SQL and JavaScript

Creating Database

  • First we will create a database
  • Go to phpmyadmin (localhost/phpmyadmin)
  • Create a database
  • Create a table inside the database named users
php mysql insert

Creating Database

I have created a table name users. In users I have three columns (id, username and password) as you can see above. Id is primary key with an auto increment. So we will insert only username and password with our html form.

Creating HTML Form to Insert Values in Database

  • Now we will create our html form.
  • You can use the below html code to create your form.

index.html
XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
 
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
        <script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
 
<body>
<form action='insert.php' method='post' id='myform' >
<p>
<input type='text' name='username' placeholder='user name' id='username' />
</p>
 
<p>
<input type='text' name='password' placeholder='password' id='password' />
</p>
<button id='insert'>Insert</button>
<p id='result'></p>
</form>
</body>
</html>

  • As you can see we have one form with action = insert.php i.e. when we click on the button we will be redirected to insert.php.
  • The method is post and we have also given an id to our form which is myform.
  • The form has two inputs, one for username and other for password with name and id attribute.
  • We will use the id attribute to access the values from jQuery. So we have also added the jQuery file inside the head tag.
  • And at last we have a p element with an id result. This is to show the success message after successful insertion.
  • The above form will generate following output.
php mysql insert tutorial

index.html

Creating PHP Script to Insert Values in Database

  • Create a file named insert.php
  • First we will connect to our database.
  • For connecting we will define some constants.

insert.php
PHP
1
2
3
4
5
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','test');

  • Now we will connect to our database using the constants we defined.

insert.php
PHP
1
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);

  • Get the values which are coming from our form using post method.

insert.php
1
2
$username = $_POST['name'];
$pass = $_POST['pass'];

  • Finally we will insert these values into our database

insert.php
PHP
1
2
3
4
5
6
$sql = "insert into users (name, password) values ('$username','$pass')";
if(mysqli_query($con, $sql)){
echo 'success';
}
?>

  • Your final php script for php mysql insert project is

php mysql insert - final php code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','mydatabase');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$username = $_POST['name'];
$pass = $_POST['pass'];
$sql = "insert into users (username, password) values ('$username','$pass')";
if(mysqli_query($con, $sql)){
echo 'success';
}
?>

  • Now try running your project.
  • It is working fine but we are getting redirected to insert.php. Our task is to insert without refreshing our redirecting the page. For this we will use jQuery AJAX method.

Using jQuery AJAX Methods to insert values in database without refreshing the page

  • Create a new file name insert.js
  • Add your insert.js to your html file below the form

index.html
1
<script src='insert.js'></script>

  • First we will stop our form from getting redirected to insert.php

insert.js
JavaScript
1
2
3
$('#myform').submit(function(){
return false;
});

  • Try clicking insert button now, nothing will happen. 😛
  • Now we will execute our php script in background using jQuery post method.

insert.js
JavaScript
1
2
3
4
5
6
7
$.post(
'script to execute',
'values to send',
function(result){
//get the output of the script
}
);

  • We will use the above post method inside the click function of our button
  • So our final insert.js will be

insert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
$('#myform').submit(function(){
return false;
});
 
$('#insert').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});

  • Try running your project now. It is working fine the values are getting inserted in database without refreshing our page.
  • You can also download the project source from the link given below. And if you are having any confusion or doubts following the steps feel free to comment. Thank You 🙂

[download id=”1400″] 

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: PHP Advance, PHP Tutorial Tagged With: insert into database without refresh, php ajax jquery tutorial, php mysql insert into database

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. ezpayrecharge says

    July 24, 2015 at 4:42 pm

    Login & Register form

    Reply
  2. Haryo says

    September 20, 2015 at 1:15 am

    Your way inserting data into database is not working when the file of insert.php saved in deepest folder. so “return false” failed!

    <form action='folder1/folder2/folder3/folder4/insert.php' ……..

    Could you give me the solutions..?

    Thx, Rgds
    Haryo

    Reply
    • Haryo says

      September 20, 2015 at 1:26 am

      Ups Sorry, I made a lil’ mistake on saving insert.js

      🙂 Good Job! it is working fine…

      Thanks, I will use this way.

      Rgds,
      Haryo

      Reply
  3. Victor says

    October 10, 2015 at 2:30 pm

    Well done. This is what I wanted all along.

    Just came from VB Programming to the advanced Web bassed application.

    Thank you. You have made my day./ career.

    Reply
    • Belal Khan says

      October 10, 2015 at 3:08 pm

      Thank you keep visiting 🙂

      Reply
  4. Jean says

    October 28, 2015 at 2:52 pm

    Thank you for the great job. I am able to get the database updated and success message. But it doesn’t empty the form. so same data can be submitted over and over. Ho can I fix that?

    Reply
  5. Belal Khan says

    October 28, 2015 at 3:04 pm

    use the val function to empty the form $(‘#inputfield’).val(”);

    Reply
    • alice says

      December 19, 2016 at 10:10 am

      Hi, nice work!

      Where should I add this code $(‘#inputfield’).val(”); to clear the form?

      Thank you

      Reply
  6. achoda says

    November 2, 2015 at 9:25 am

    this is owesome.
    help me with a tutorial to insert data from a listview to mysql database

    Reply
    • Belal Khan says

      November 2, 2015 at 1:13 pm

      You can do it with a little changes..

      Reply
  7. shubham says

    November 5, 2015 at 7:27 am

    code are awsom plus helpful. But I have a problem, still am reaching to insert.php.

    Reply
    • Belal Khan says

      November 5, 2015 at 7:34 am

      What do you mean??

      Reply
      • shubham says

        November 5, 2015 at 8:20 am

        I mean to say ..
        ham chate hai ki insert.php meh na jaye when we click on insert button .
        index.html meh hi sara process hojaye.

        Reply
        • Belal Khan says

          November 5, 2015 at 12:45 pm

          that is what we are doing here.. Everything is happening on index.html..

          Reply
  8. shubham says

    November 5, 2015 at 3:50 pm

    I did what all you have done here. Starting from creating index.php then insert.php and insert.js.
    I added insert.js below the form inside the index.php and written action = “insert.php”.But still when I click on insert button, it shows success message in insert.php page which I don’t want. If you have a tutorial video in youtube then please let me know.
    Thank You.

    Reply
    • Belal Khan says

      November 5, 2015 at 5:37 pm

      connect with me on facebook.com/Probelalkhan and i will try to help u

      Reply
      • soham says

        December 21, 2016 at 12:05 pm

        I am getting the same problem

        Reply
  9. shubham says

    November 6, 2015 at 5:49 am

    okh bro

    Reply
  10. Mufaro says

    November 11, 2015 at 1:17 pm

    You r the best!!!!!!!

    Reply
  11. Benjamin says

    January 5, 2016 at 6:48 am

    Hey I got this nearly working. You see I am using more than one form on a page… an add to cart button on serveral products.

    I have changed the form id to form id from myform to myform12 or what ever the prod code is and have also changed the insert id accordingly as well. Then in the js code I have changed all of the ids to match the ones in my form.

    The problem i get is that my input values are not passing to the insert script. I get an Notice: Undefined index on the variables in the insert script 🙁

    Any ideas?

    Reply
  12. Piyush says

    January 11, 2016 at 6:20 am

    how to upload multiple images in database and image folder without page refresh?

    Reply
  13. Lukman Pathan says

    April 5, 2016 at 4:18 pm

    hi
    i have one template in which i can add rows dynamically through java script.
    now i wanted to add each row as a one record in my database (php mysql).
    i m beginner to php so cant handle it… can u pls help

    Reply
  14. Nik says

    August 2, 2016 at 2:09 pm

    Thank you nice example

    Reply
  15. [email protected] says

    August 3, 2016 at 4:42 am

    Hello ,
    I have 1 page and four form tag which are step by step form i want to insert one by one page using ajax i serialize the form by its id but i get output with original text but with that original text there are add “+++++” sign into output,so i can not get proper output how can i fix the problem?

    Reply
  16. nirav says

    October 3, 2016 at 9:23 am

    nice code

    Reply
  17. M.Suamir Kalim says

    January 19, 2017 at 9:16 pm

    thanks its working

    Reply
  18. Aymen says

    May 2, 2017 at 10:18 pm

    Thank you it’s working ^^

    Reply
  19. ARUN RAJ KUMAR D says

    May 26, 2017 at 11:45 am

    My best wishes.
    Your tutorials are helpful for my life

    Thanks

    Reply
  20. ravi gohel says

    June 16, 2018 at 12:18 pm

    use append function in javascript
    so you can add dynamically row add

    Reply
  21. spiers says

    October 21, 2018 at 9:38 am

    thank you so much.
    this is exactly what i have been looking for.
    but what about if i have two form on one page. how do i handle that.

    Reply

Leave a Reply to Aymen Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.