Editing a Database Record in PHP
Let's now implement user editing.
For this, we will need two pages: the
edit.php page, which will host the
form for editing the user, and the
save.php page, to which the form will be submitted
for subsequent saving.
Edit Page
First, on the edit.php page, let's create a
form:
<form action="" method="POST">
<input name="name">
<input name="age">
<input name="salary">
<input type="submit">
</form>
We will load the current user data
from the database into this form.
Let the user's id
for editing be passed in the GET
parameter:
<?php
$id = $_GET['id'];
?>
Let's form a query to get the user:
<?php
$query = "SELECT * FROM users WHERE id=$id";
?>
Let's execute the query:
<?php
$result = mysqli_query($link, $query) or die(mysqli_error($link));
?>
Let's get the user data into a variable:
<?php
$user = mysqli_fetch_assoc($result);
?>
Let's output this data in our form:
<form method="POST">
<input name="name" value="<?= $user['name'] ?>">
<input name="age" value="<?= $user['age'] ?>">
<input name="salary" value="<?= $user['salary'] ?>">
<input type="submit">
</form>
Let's change the form's action so that it
is submitted to the save.php page:
<form action="save.php" method="POST">
In this case, we will pass the user's
id for editing as a GET parameter:
<form action="save.php?id=<?= $_GET['id'] ?>" method="POST">
Save Page
On the save.php page, let's get the submitted
data:
<?php
$id = $_GET['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$salary = $_POST['salary'];
?>
Let's form an update query:
<?php
$query = "UPDATE users SET
name='$name', age='$age', salary='$salary'
WHERE id=$id";
?>
Let's execute the query:
<?php
mysqli_query($link, $query) or die(mysqli_error($link));
?>
Let's output a message about the successful operation:
<?php
echo 'User successfully updated!';
?>
Practical Tasks
Implement the edit.php page for editing
a user.
Implement the save.php page for saving
the editing result.
On the index.php page, display
a list of users so that for each
user there is a link to edit them:
<ul>
<li>user1 <a href="?edit=1">edit</a></li>
<li>user2 <a href="?edit=2">edit</a></li>
<li>user3 <a href="?edit=3">edit</a></li>
</ul>
Implement form processing on the edit.php page.