F - Update
A company stores employee information in a MySQL database. The company needs a web interface that allows staff to select an employee and update their details.
Create a PHP and MySQL system with two pages.
Page 1: Employee Records
The page should:
- Connect to the employees database.
- Retrieve all employee records.
- Display the records in a table.
- Display the employee’s ID, name, email and job.
- Include a radio button for each employee.
- Allow only one employee to be selected.
- Use a form with an Edit Employee submit button.
- Send the selected employee’s ID to the edit page.
Page 2: Edit Employee
The page should:
- Receive the selected employee’s ID.
- Retrieve that employee’s details from the database.
- Display the details in a form.
- Allow the user to change the name, email and job.
- Use an Update Employee submit button.
- Update the selected record in the database.
- Return to the Employee Records page after the update.
Task
<?php
$conn = mysqli_connect("localhost", "root", "", "employees");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM employees";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Employee Records</title>
</head>
<body>
<h1>Employee Management</h1>
<h2>Employee Records</h2>
<p>Select an employee from the list and click Edit Employee to update their details.</p>
<form action="edit.php" method="get">
<table border="1">
<tr>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Job</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>";
echo "<input type='radio' name='id' value='" . $row['id'] . "' required>";
echo "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['job'] . "</td>";
echo "</tr>";
}
?>
</table>
<br>
<input type="submit" value="Edit Employee">
</form>
</body>
</html>
<?php
mysqli_close($conn);
?>
BEGIN
CONNECT TO employees database
GET employee ID from URL
SELECT employee WHERE ID matches selected ID
STORE employee details
DISPLAY employee details in a form
IF Update Employee button is pressed THEN
GET ID from form
GET name from form
GET email from form
GET job from form
UPDATE employee record
WHERE ID matches selected ID
REDIRECT to Employee Records page
END IF
END