What best practices should be followed when renaming columns in a MySQL table using PHP?

When renaming columns in a MySQL table using PHP, it is important to follow best practices to ensure the integrity of the data. One approach is to use the ALTER TABLE statement in MySQL to rename the column. It is also recommended to check if the column exists before renaming it to avoid any errors.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Check if column exists
$column_name = 'old_column_name';
$sql = "SHOW COLUMNS FROM table_name LIKE '$column_name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // Rename column
  $new_column_name = 'new_column_name';
  $sql = "ALTER TABLE table_name CHANGE $column_name $new_column_name INT(11)";
  
  if ($conn->query($sql) === TRUE) {
    echo "Column renamed successfully";
  } else {
    echo "Error renaming column: " . $conn->error;
  }
} else {
  echo "Column does not exist";
}

$conn->close();
?>