Update data

To update table data in PHP, you can use the following steps:

  1. Create an HTML form with the necessary input fields for updating the data.

  2. Submit the form to a PHP script that handles the update operation.

  3. In the PHP script, connect to the database and update the desired row(s) with the new data.

  4. Display a success message to the user.

Here's an example of how to update data in a MySQL database using PHP:

HTML form (update_form.html):

<!DOCTYPE html>
<html>
<head>
  <title>Update Form</title>
</head>
<body>
  <h1>Update Form</h1>
  <?php
  // Retrieve the ID from the URL parameter
  $id = $_GET['id'];
  // Connect to the database
  $conn = mysqli_connect("localhost", "root", "", "PHP_experiment");
  // Check connection
  if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
  }
  // Query to retrieve the row with the specified ID from the 'users' table
  $sql = "SELECT * FROM users WHERE id=$id";
  $result = mysqli_query($conn, $sql);
  // Fetch the row as an associative array
  $row = mysqli_fetch_assoc($result);
  // Close the database connection
  mysqli_close($conn);
  ?>
  <form action="update.php" method="POST">
    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
    <label>Name:</label>
    <input type="text" name="name" value="<?php echo $row['name']; ?>"><br>
    <label>Email:</label>
    <input type="email" name="email" value="<?php echo $row['email']; ?>"><br>
    <input type="submit" name="submit" value="Update">
  </form>
</body>
</html>

update.php:

<?php
// Connect to the database
$conn = mysqli_connect("localhost", "root", "", "PHP_experiment");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Get the values from the form
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];

// Update the data in the database
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
    echo "Data updated successfully!";
} else {
    echo "Error updating data: " . mysqli_error($conn);
}

// Close the database connection
mysqli_close($conn);
?>

Last updated