What are some best practices for updating values in MySQL tables using PHP to ensure data integrity?
When updating values in MySQL tables using PHP, it is important to ensure data integrity by properly sanitizing user input to prevent SQL injection attacks. One best practice is to use prepared statements with placeholders to bind parameters securely. Additionally, validate input data to ensure it meets the expected format and constraints before updating the database.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare SQL statement with placeholders
$stmt = $mysqli->prepare("UPDATE table_name SET column_name = ? WHERE id = ?");
// Bind parameters securely
$stmt->bind_param("si", $new_value, $id);
// Sanitize and validate input data
$new_value = filter_var($_POST['new_value'], FILTER_SANITIZE_STRING);
$id = filter_var($_POST['id'], FILTER_VALIDATE_INT);
// Execute the statement
$stmt->execute();
// Close the statement and connection
$stmt->close();
$mysqli->close();