In PHP, after connecting to a MySQL database using mysqli_connect() , sometimes we need to check the charset of the currently connected. The mysqli::get_charset function can easily get the character set used by the current connection. This article will explain how to use the mysqli::get_charset function to check the current character set after connecting to the database.
Here is a simple PHP code example that demonstrates how to connect to a MySQL database and check the current character set immediately after the connection is successful:
<?php
// Database connection information
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check if the connection is successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Set the character set to UTF-8
mysqli_set_charset($conn, "utf8");
// use mysqli::get_charset Check the current character set
$current_charset = mysqli_character_set_name($conn);
echo "The current character set is: " . $current_charset;
// Close the connection
mysqli_close($conn);
?>
Connect to the database <br> We first use the mysqli_connect() function to connect to the database. The passed parameters include the address of the database server ( localhost in this example), username, password, and database name.
Check if the connection is successful <br> Use if (!$conn) to determine whether the connection is successful. If the connection fails, use the die() function to output the error message and terminate the script execution.
Set character set <br> Set the connected character set to UTF-8 by mysqli_set_charset($conn, "utf8") . This ensures that the data is processed correctly when both inserted and queried.
Check character set <br> Get the character set name of the currently connected character set via mysqli_character_set_name($conn) and output it to the page.
Close the connection <br> Use mysqli_close($conn) to close the connection to the database and free up resources.
After connecting to the database using the mysqli_connect() function, the current character set can be easily checked through the mysqli::get_charset function. This is very important to ensure character set consistency and avoid garbled problems. Especially in multilingual website development, setting the correct character set is the key to ensuring the normal display of data.