Insert Data into MySQL database with PHP and AJAX without refreshing the page (Source Code)

 

 

 

 

 

 

 

What you need?

  • WAMP
  • Dreamweaver / Notepad
  • Some knowledge of creating mysql database

First of all you need to create a database. Install WAMP if you have not installed yet. Open http://localhost/phpmyadmin/ and log in. Create a database with the nameĀ insertdb. Copy the below SQL to create the required tables.

Database:

— phpMyAdmin SQL Dump
— version 4.8.4
— https://www.phpmyadmin.net/

— Host: 127.0.0.1:3306
— Generation Time: Apr 07, 2019 at 08:29 AM
— Server version: 5.7.24
— PHP Version: 5.6.40

SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = “+00:00”;

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;


— Database: `insertdb`

— ——————————————————–


— Table structure for table `users`

DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
`password` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;


— Dumping data for table `users`

INSERT INTO `users` (`id`, `username`, `password`) VALUES
(1, ‘abc’, ‘def’),
(2, ‘ade’, ‘dfe’),
(3, ‘efd’, ‘efe’),
(4, ‘dfe’, ‘dfe’);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


Open notepad or dreamweaver to create a file and name it index.php. Write the below code.

index.php

<!DOCTYPE html>
<html>
<head>
<title>Insert Data into MySQL database with PHP and AJAX without refreshing the page (Source Code)</title>
<script src=’https://code.jquery.com/jquery-2.1.3.min.js’></script>
</head>
<body>
<form action=’insertconn.php’ method=’post’ id=’insertform’ >
<p>
<input type=’text’ name=’username1′ placeholder=’user name’ id=’username’ />
</p>
<p>
<input type=’text’ name=’password1′ placeholder=’password’ id=’password’ />
</p>
<button id=’insert’>Insert</button>
<p id=’result’></p>
</form>

<script>
$(‘#insertform’).submit(function(){
return false;
});
$(‘#insert’).click(function(){
$.post(
$(‘#insertform’).attr(‘action’),
$(‘#insertform :input’).serializeArray(),
function(result){
$(‘#result’).html(result);
$(“#username”).val(“”);
$(“#password”).val(“”);
}
);
});
</script>
</body>
</html>


insertconn.php

<?php

$con = mysqli_connect(“localhost”,”root”,”root”,”insertdb”);
$username1 = $_POST[‘username1’];
$password1 = $_POST[‘password1’];
$query = “insert into users (username, password) values (‘$username1′,’$password1’)”;

if(mysqli_query($con, $query)){
echo ‘Record has been added!’;
}

?>