Change the charset on the MySQL connection

By | July 31, 2017

Change the charset on the MySQL connection,Default MySQL character set and collation,PHP mysqli_set_charset() Function,convert a MySQL database to UTF-8 encoding

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 can be totally valid for our purposes. While our application may have needs to work with another charset such as UTF8. For this case we can change the charset in the connection.

Change the charset on the MySQL connection

Change the charset on the MySQL connection

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

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

If ( $ db -> connect_error )
Die ( 'Connection Error (' . $ Db -> connect_errno . ')' . $ Db -> connect_error ) ;

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

Echo "Using a charset, by default, type:" . $ Db -> character_set_name ( ) ;

If we execute it we will see as we see that the answer is “latin1”.

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

$ Db -> set_charset ( 'utf8' ) ;

How to convert MYSQL data to JSON using PHP

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

learn about connection Character Sets and Collations click hereĀ 

Leave a Reply

Your email address will not be published. Required fields are marked *