Skip to content

Specifying the MySQL character set in PHP

When connecting to a MySQL database, it is important to specify the correct character set to ensure proper storage and retrieval of text data. On ruachost.com, you can configure this directly in your PHP connection code.

  • Prevents issues with accented characters, symbols, and multilingual text.
  • Ensures consistent encoding between your database and application.
  • Avoids data corruption when storing or retrieving text.
  • Supports internationalization for global applications.

To see which character sets are available on your server:

Terminal window
grep "charset name" /usr/share/mysql/charsets/Index.xml | cut -f2 -d '"'

This command lists the supported values you can use in your PHP connection.

If you are connecting with MySQLi, use the set_charset method:

<?php
$mysqli = new mysqli("localhost", "dbuser", "password", "database");
$mysqli->set_charset("utf8");
?>
  • utf8 is commonly used for Unicode support.
  • You can replace it with another supported character set (e.g., cp1256 for Windows Arabic).

If you are connecting with PDO, include the charset parameter in the DSN string:

<?php
$myPDO = new PDO(
'mysql:host=localhost;dbname=database;charset=utf8',
'dbuser',
'password'
);
?>
  • This ensures all queries and results use the specified character set.
  • Recommended for applications requiring portability across databases.