Update and Save data in database using PHP
To update record in database initially we need to add edit button in html form. Edit button helps you to edit record in database. Here we need html form which provide field to edit data. We have first select particular record from database and fetch in html form after that only we can edit record.
Database query to get record in html form is as follow:
Syntax is here:
"SELECT * FROM Table_name WHERE Clause Condition"
Below we have code to edit data in html form in edit.php file:
<!--php form execution-->
<?php
$conn=new mysqli('localhost','root','','vibha');
if(isset($_GET['id']))
{
$id=$_GET['id'];
$query="SELECT * FROM registration WHERE id='$id' ";
$result=mysqli_query($conn,$query);
$row=mysqli_fetch_array($result);
}
?>
<!--edit form-->
<!DOCTYPE html>
<html>
<head>
<title>Edit data in database</title>
</head>
<body>
<h1> Edit Form </h1>
<form action="save.php" method="POST">
Id<input type="text" name="id" value="<?php echo $row['id'];
?>"><br>
FirstName<input type="text" name="FirstName" value="<?php echo
$row['FirstName'];?>"><br>
LastName<input type="text" name="LastName" value="<?php echo
$row['LastName'];?>"><br>
Email<input type="email" name="Email" value="<?php echo
$row['Email']; ?>"><br>
MobileNo<input type="text" name="MobileNo" value="<?php echo
$row['MobileNo']; ?>"><br>
<input type="submit" name="submit" value="save">
</form>
</body>
</html>
Lets learn how to update record in database we need to click on save button added in html form in edit.php where you have fetch record from database.
Update Query is required to update data in database.
Syntax is as follow:
"UPDATE Table_name SET Column_name1, Column_name2.... WHERE Column_name(primary key) "
Below is code file which is used to update record in database. It is save.php.
<!--php code for save-->
<?php
$conn=new mysqli('localhost','root','','vibha');
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$fname=mysqli_real_escape_string($conn,$_POST['FirstName']);
$lname=mysqli_real_escape_string($conn,$_POST['LastName']);
$email=mysqli_real_escape_string($conn,$_POST['Email']);
$mobile=mysqli_real_escape_string($conn,$_POST['MobileNo']);
$query="UPDATE registration SET FirstName='$fname',
LastName='$lname', Email='$email', MobileNo='$mobile'
WHERE id='$id'";
$result=mysqli_query($conn,$query);
header('location:retrive.php');
}
?>
Comments
Post a Comment