What are some best practices for structuring and organizing PHP code to handle editing values in a table efficiently?

When editing values in a table efficiently in PHP, it is best practice to use prepared statements to prevent SQL injection attacks and improve performance. Additionally, organizing your code into separate functions for connecting to the database, retrieving data, updating values, and handling errors can make the code more maintainable and easier to debug.

<?php
// Function to connect to the database
function connectToDatabase() {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";

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

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

    return $conn;
}

// Function to update values in the table
function updateTableValue($id, $newValue) {
    $conn = connectToDatabase();

    $stmt = $conn->prepare("UPDATE table_name SET column_name = ? WHERE id = ?");
    $stmt->bind_param("si", $newValue, $id);

    if ($stmt->execute() === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $conn->error;
    }

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

// Usage example
$id = 1;
$newValue = "New Value";
updateTableValue($id, $newValue);
?>