What are some best practices for updating data in PHP using SQL queries?

When updating data in PHP using SQL queries, it is important to follow best practices to ensure the security and efficiency of the process. One key practice is to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to validate and sanitize user input before executing the update query. Finally, always remember to handle errors gracefully to provide a better user experience.

<?php
// Establish a connection to the 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);
}

// Update data in the database using prepared statements
$stmt = $conn->prepare("UPDATE table_name SET column1 = ? WHERE id = ?");
$stmt->bind_param("si", $value1, $id);

// Set parameters and execute
$value1 = "new_value";
$id = 1;
$stmt->execute();

echo "Record updated successfully";

// Close the statement and connection
$stmt->close();
$conn->close();
?>