What are some best practices for altering a MySQL table structure using PHP?

When altering a MySQL table structure using PHP, it is important to follow best practices to ensure data integrity and avoid any potential issues. Some best practices include taking a backup of the database before making any changes, using transactions to group multiple queries together, and validating user input to prevent SQL injection attacks.

// Backup the database before making any changes
$backupFile = 'backup.sql';
exec("mysqldump -u username -ppassword database_name > $backupFile");

// Start a transaction to group multiple queries together
$pdo->beginTransaction();

// Alter the table structure
$query = "ALTER TABLE table_name ADD COLUMN new_column INT";
$pdo->exec($query);

// Commit the transaction
$pdo->commit();

// Validate user input to prevent SQL injection attacks
$newColumnValue = filter_input(INPUT_POST, 'new_column_value', FILTER_SANITIZE_STRING);
$query = "UPDATE table_name SET new_column = :value WHERE id = :id";
$statement = $pdo->prepare($query);
$statement->bindParam(':value', $newColumnValue);
$statement->bindParam(':id', $id);
$statement->execute();