A Comprehensive Guide on mysqli_set_charset Function in PHP
When it comes to working with MySQL databases in PHP, the mysqli extension provides a variety of functions to perform various operations. One such function is
When you store names, comments, or emoji in MySQL, the bytes only round-trip correctly if PHP and the database agree on a character set — the mapping between bytes and characters. The mysqli_set_charset function sets the character set for the connection between your PHP script and the MySQL server, so everything you send and receive is interpreted the same way on both sides.
This page explains what the function does, why setting the charset on the connection matters (and why it is also a security measure), and how to use it with both the procedural and object-oriented mysqli APIs.
What mysqli_set_charset does
mysqli_set_charset tells the MySQL server which character set the client (your PHP script) will use for the rest of the connection. It affects how query strings are interpreted, how results are encoded on the way back, and which bytes mysqli_real_escape_string() treats as special.
The procedural signature takes the connection first and the charset name second, and returns true on success or false on failure:
mysqli_set_charset(mysqli $connection, string $charset): boolThe object-oriented form is a method on the connection object:
$connection->set_charset($charset);The $charset argument is a MySQL character-set name such as utf8mb4, utf8, or latin1 — not a PHP encoding name. Use utf8mb4 for full Unicode support, including 4-byte characters like emoji; the older utf8 alias in MySQL only stores up to 3 bytes per character and cannot hold emoji.
Set it on the connection, not just in queries. Running
SET NAMES utf8mb4as a query changes the server-side charset but does not update the value the C client library uses for escaping.mysqli_set_charsetupdates both, which is why it is the correct and safe way to switch charsets.
Connecting and setting the charset
mysqli_set_charset needs an existing connection, so first open one with mysqli_connect. The example below connects, then immediately sets utf8mb4:
<?php
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'mydatabase';
$connection = mysqli_connect($host, $user, $password, $database);
if (!$connection) {
die('Connection failed: ' . mysqli_connect_error());
}
if (!mysqli_set_charset($connection, 'utf8mb4')) {
die('Error setting charset: ' . mysqli_error($connection));
}
echo 'Current charset: ' . mysqli_character_set_name($connection);
// Current charset: utf8mb4After the call succeeds, mysqli_character_set_name reports the active charset, confirming the change took effect.
Object-oriented example
If you use the object-oriented mysqli API, call set_charset() as a method. It is good practice to do this right after constructing the connection, before running any query:
<?php
$mysqli = new mysqli('localhost', 'username', 'password', 'mydatabase');
if ($mysqli->connect_errno) {
die('Connection failed: ' . $mysqli->connect_error);
}
if (!$mysqli->set_charset('utf8mb4')) {
die('Error setting charset: ' . $mysqli->error);
}
echo $mysqli->character_set_name();
// utf8mb4Handling failure
mysqli_set_charset returns false if the server does not support the requested charset (for example, a typo like utf8mb44). Always check the return value rather than assuming success:
<?php
if (!mysqli_set_charset($connection, 'utf8mb4')) {
// Log it and stop — running queries with the wrong charset
// can corrupt stored text and weaken escaping.
throw new RuntimeException(
'Failed to set charset: ' . mysqli_error($connection)
);
}You can call the function more than once on the same connection to switch charsets mid-session, though in practice you set it once right after connecting and leave it.
Why it matters
- Correct text. Without a matching charset, accented letters and non-Latin scripts come back as
?or mojibake (garbled characters likeéinstead ofé). - Emoji and full Unicode. Only
utf8mb4stores 4-byte characters;utf8silently drops or truncates them. - Security.
mysqli_real_escape_string()escapes based on the connection charset. Setting it correctly closes a class of SQL-injection vectors that exploit multibyte mismatches. Even so, prefer prepared statements over manual escaping.
Related functions
mysqli_connect— open the connection you pass toset_charset.mysqli_get_charset— get a full object describing the current charset (collation, comment, number).mysqli_character_set_name— get just the name of the active charset.mysqli_select_db— switch the active database on an existing connection.
Conclusion
mysqli_set_charset aligns the character set of your PHP script with your MySQL connection, ensuring text round-trips correctly and that escaping behaves safely. Set it to utf8mb4 right after connecting, check its return value, and you have covered the common cases — from accented names to emoji.