What role does collation play in PHP when dealing with character encoding and data manipulation in databases?

When dealing with character encoding and data manipulation in databases, collation plays a crucial role in ensuring that the data is stored and retrieved correctly. Collation defines how the data is sorted and compared, taking into account the character set and encoding used. It is important to set the appropriate collation for your database tables to avoid issues with sorting, searching, and comparing text data.

// Set collation for a database table in PHP
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

// Set collation for a specific table
$sql = "ALTER TABLE table_name COLLATE utf8_general_ci";
if ($conn->query($sql) === TRUE) {
    echo "Collation set successfully";
} else {
    echo "Error setting collation: " . $conn->error;
}

// Close connection
$conn->close();