How can the database connection in PHP be configured to use UTF-8 encoding?
To configure the database connection in PHP to use UTF-8 encoding, you can set the charset to UTF-8 in the connection string or use the mysqli_set_charset function after establishing the connection. This ensures that data is stored and retrieved in the correct character encoding, preventing issues with special characters or international text.
// Using charset in the connection string
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Using mysqli_set_charset function
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");