How can duplicate database connections in PHP scripts lead to issues with character encoding, and what is the best approach to handle database connections in PHP scripts?

Duplicate database connections in PHP scripts can lead to character encoding issues because each connection may have its own default character set, collation, or encoding settings. To handle database connections in PHP scripts, it is best to use a single database connection throughout the script execution and ensure that the connection settings are consistent with the character encoding requirements of the database.

// Create a single database connection and set the character encoding
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Set character encoding
$conn->set_charset("utf8");