What best practices should be followed when updating database records based on calculations in PHP?

When updating database records based on calculations in PHP, it is important to ensure data integrity by properly sanitizing user input and using prepared statements to prevent SQL injection attacks. Additionally, it is recommended to validate the input data before performing any calculations to avoid errors and unexpected results. Lastly, always remember to handle errors gracefully and provide appropriate feedback to the user.

<?php
// Assuming $conn is the database connection object

// Sanitize user input
$userId = filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
$newValue = filter_var($_POST['new_value'], FILTER_SANITIZE_NUMBER_FLOAT);

// Validate input data
if (!is_numeric($userId) || !is_numeric($newValue)) {
    die("Invalid input data");
}

// Perform calculations
$updatedValue = $newValue * 2;

// Update database record using prepared statement
$stmt = $conn->prepare("UPDATE table_name SET column_name = ? WHERE user_id = ?");
$stmt->bind_param("ii", $updatedValue, $userId);
$stmt->execute();

if ($stmt->affected_rows > 0) {
    echo "Record updated successfully";
} else {
    echo "Failed to update record";
}

$stmt->close();
$conn->close();
?>