# Specifying the MySQL character set in PHP

> Set the right MySQL character set in your PHP connection code with MySQLi or PDO to avoid garbled text.

Source: https://helpcenter.ruachost.com/developers/php/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.

## Why Specify a Character Set?

- 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.

## Determining Available Character Sets

To see which character sets are available on your server:

```bash
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.

## Using the MySQLi Extension

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).

## Using PDO (PHP Data Objects)

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.

> **Best Practices:**
- Always use `utf8mb4` instead of `utf8` for full Unicode support (including emojis and extended characters).
- Match the PHP connection character set with the database table’s collation.
- Test queries to confirm proper encoding and decoding of multilingual data.
