What are some best practices for allowing users to edit and save data in a table using PHP?

When allowing users to edit and save data in a table using PHP, it is important to follow best practices to ensure data integrity and security. One approach is to use prepared statements to prevent SQL injection attacks and validate user input to avoid errors. Additionally, consider implementing a form validation process to ensure that only valid data is submitted for editing.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate input
    $id = $_POST['id'];
    $newData = $_POST['newData'];

    // Update data in database
    $stmt = $conn->prepare("UPDATE table SET data = ? WHERE id = ?");
    $stmt->bind_param("si", $newData, $id);

    if ($stmt->execute()) {
        echo "Data updated successfully";
    } else {
        echo "Error updating data: " . $conn->error;
    }

    $stmt->close();
}

$conn->close();
?>