.


Divya

How to edit or update Data using PHP Ajax



Here we using 2 file for update data from MySql database using Ajax.

  1. index.php
  2. update-ajax.php

Table user_data

CREATE TABLE `user_data` (
`id` int(11) NOT NULL,
`Name` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.php

<?php
$con=mysqli_connect("localhost","root","","php_ajax");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM user_data");
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
table, td, th {
border: 1px solid #ddd;
text-align: left;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 15px;
}
</style>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>StudentName</th>
<th>Student Email</th>
<th>Action</th>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<input type="hidden" name="id[]" id=<?php echo "id".$i; ?> value="<?php echo $row["id"]; ?>">
<td ><?php echo $row["id"]; ?></td>
<td><input type="text" id=<?php echo "name".$i; ?> value="<?php echo $row["Name"]; ?>"></td>
<td><input type="text" id=<?php echo "email".$i; ?> value="<?php echo $row["email"]; ?>"></td>
<td style="width:270px"><button type="button" id=<?php echo "update".$i; ?> name="submit" class="update btn btn-success">Edit</button>
</td>
</tr>
<?php
$i++;
}
?>
</table>
<script>
$(".update").click(function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( this.status == 200) {
location.reload();
}
};
var thisId=this.id;
var numPart=thisId.substring(6,7);
var idEle=document.getElementById("id"+numPart);
var unitEle=document.getElementById(numPart);
var nameEle=document.getElementById("name"+numPart);
var emailEle=document.getElementById("email"+numPart);
var x="update-ajax.php?id="+idEle.value+"&name="+nameEle.value+"&email="+emailEle.value;
xmlhttp.open("GET", x, true);
xmlhttp.send();
});
</script>
</body>
</html>

update-ajax.php

<?php
$conn=mysqli_connect("localhost","root","","php_ajax");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$query = "UPDATE `user_data` SET `Name`='$name',`email`='$email' WHERE id = '".$_GET['id']."'";
echo("alert('$query');");
$result = mysqli_query($conn,$query) or die(mysqli_error());
echo("alert('$result');");
exit(json_encode($_POST));
?>


.