This project demonstrates how to dynamically add rows into an HTML table using jQuery + AJAX and store them in a MySQL database using PHP.
- Add rows dynamically without page reload
- Remove rows instantly
- Save multiple rows at once
- Fetch data from database
index.php
config.php
action-form.ajax.php
CREATE TABLE `reorderusers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(64) NOT NULL,
`useremail` varchar(128) NOT NULL,
`userphone` varchar(24) NOT NULL,
`usercountry` int(11) NOT NULL,
`dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);INSERT INTO `reorderusers` (`username`, `useremail`, `userphone`, `usercountry`) VALUES
('Jhon', 'john@example.com', '0808254552', 23),
('Aslam', 'aslam@example.com', '5400897855', 20),
('Kartik', 'kartik@example.com', '1555420004', 50),
('Jordan', 'jordan@example.com', '8975421200', 100);<?php
define('DB_NAME', 'YOUR_DB_NAME');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>$(document).ready(function() {
$("#addmore").click(function() {
$.ajax({
type: 'POST',
url: 'action-form.ajax.php',
data: { action: 'addDataRow' },
success: function(data) {
$('#tb').append(data);
}
});
});
});if(isset($_POST['action']) && $_POST['action']=="addDataRow"){
?>
<tr>
<td><button onclick="$(this).closest('tr').remove();">Remove</button></td>
<td><?php echo date('Y-m-d H:i:s');?></td>
<td><input type="text" name="username[]" required></td>
<td><input type="email" name="useremail[]" required></td>
<td><input type="text" name="userphone[]" required></td>
</tr>
<?php
}if(isset($_POST['action']) && $_POST['action']=="saveAddMore"){
foreach($_POST['username'] as $key => $username){
$email = $_POST['useremail'][$key];
$phone = $_POST['userphone'][$key];
$db->query("INSERT INTO reorderusers
(username, useremail, userphone)
VALUES ('$username', '$email', '$phone')");
}
echo "Saved Successfully";
}$("#form").submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'action-form.ajax.php',
data: $(this).serialize(),
success: function(response){
alert("Data Saved Successfully!");
location.reload();
}
});
});- PHP
- MySQL
- jQuery
- Use prepared statements to prevent SQL injection
- Validate user input
- Sanitize data before saving
Free to use and modify.