A small guide about UTF-8 Encoding in PHP and MySQL
Last Modified at 2019-06-30 17:21:15
As a PHP developer, we often use MySQL as a database for our projects to store data on the server and we always use English as a language while storing data into the table. In some cases like storing some special characters or symbols which are not into defined into the character set you have enabled for your table, then MySQL store that special characters into bad encoding and when you fetch the record and print that you will see some bad characters instead of special characters.
To resolve this problem, we use to set charecter set while storing special charecters and while fetching it.
There are two methods to set charecter set:
1) Via PHP function
2) Via MySQL Query1) Via PHP function:
PHP(MySQLi Driver) has two functions to set charecter set. First one is mysqli_set_charset(), which is procedural approach and second one is $conn->set_charset which is object oriented approach and $conn is connection object which is importent to use in object oriented approach.
mysqli_set_charset($conn, "utf8"); /* Procedural approach */
$conn->set_charset("utf8"); /* Object-oriented approach */2) Via MySQL Query:
In MySQL, you have run below query before inserting, updating or fetching records to take effect on current query.SET NAMES 'utf8';
Full PHP script:
<?php $servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_query("SET NAMES 'utf8'");
$sql = "SELECT name FROM users";
$result = $conn->query($sql);