How can the encoding be set when connecting to a MySQL server in PHP to avoid errors?

When connecting to a MySQL server in PHP, it's important to set the encoding to avoid potential errors with character encoding mismatches. This can be done by specifying the desired encoding in the connection parameters using the "charset" option. By setting the encoding explicitly, you ensure that data is stored and retrieved correctly from the database.

// Set the encoding to UTF-8 when connecting to a MySQL server 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 the encoding
$conn->set_charset("utf8");