Change the charset in the connection to MySQL

When we install a MySQL database, by default we are installed with a charset of type «latin1» and a collation of type «latin1_swedish_ci». This charset may be totally valid for our purposes. Although our application may need to work with another charset such as UTF8. For this case we can change the charset in the connection.

The first thing we will do is connect to the database.

@ $db = new mysqli(localhost, "user", "password", "db");

if ($db->connect_error)
  die('Connection Error ('.$db->connect_errno.')'.$db->connect_error);

Once connected to the database we can check which charset the database has configured using the function character_set_name().

echo "Using a charset, by default, of type: ".$db->character_set_name();

If we execute it we will see how we see that the response is “latin1”.

Now, to change the charset in the connection that we have established with the database, we rely on the function set_charset(), which will receive the type of charset to use for the connection as a method parameter. In our case we are going to change the charset in the connection to use ‘utf8’.

$db->set_charset('utf8');

From this moment on all information exchange on the database is done using utf8. If we run the function character_set_name() we will see that it is already a utf8 type connection.

We have already seen how easy it is to change the charset in the database connection. Another thing will be to manipulate the strings in uft8 format, but that will be for another article.