Quick Solution
To quickly set MySQL charset (for example, to utf8mb4
) using PHP for the current database connection session, you must first have access to the connection object (mysqli object), assuming it’s $mysqli
:
We can then use either procedural mysqli_set_charset
function to set MySQL charset:
mysqli_set_charset( $mysqli, 'utf8mb4' );
Or use the object oriented way:
$mysqli->set_charset( 'utf8mb4' );
That will change the charset to utf8mb4
.
The guide can be considered as completed. The below sections will give more examples on the methods.
Set MySQL charset using PHP
Prerequisites to setting MySQL charset is having access to the MySQL connection object.
We will have an example by creating the database connection by initializing mysqli
object:
$mysqli = new mysqli( 'localhost', 'user', 'password', 'database' );
Then, getting the initial charset set by the system configuration using character_set_name()
method:
$charset = $mysqli->character_set_name();
print_r( $charset );
If the charset is not as expected, now it’s the time to change them. Having the $mysqli
connection object, it is now easy to set MySQL charset using the two introduced ways.
1. Set MySQL charset by mysqli_set_charset
function
mysqli_set_charset( $mysqli, 'utf8mb4' );
2. Object oriented style:
$mysqli->set_charset( 'utf8mb4' );
We can verify the changed charset using character_set_name()
again.
Final Thoughts
It is very easy to set MySQL charset using PHP. To show all of the supported charset installed with your MySQL/MariaDB, you can use MySQL’s SHOW_CHARACTER_SET
command.
For more information: