# 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):

```php
<!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
<?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);
?>

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dhrubo.gitbook.io/programming-with-js/php/build-a-simple-web-application/update-data.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
