How to insert Unicode in MySQL table and read unicode data using php
How to insert Unicode in MySQL table and read unicode data using php
to store unicode charachter in amy mysql database table, we need to change the “Collation” of the column where
we want to store the data.
We can do this using PHPMyAdmin
OR, we can use the following sql statement to create the same table:
CREATE TABLE IF NOT EXISTS `mytable` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
PRIMARY KEY (`id`)
)
Read Unicode data using PHP from MySQL :
The following code will read unicode data from a mysql table:
header('Content-Type: text/html; charset=utf-8');
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die(‘Could not connect: ‘ . mysql_error());
}
mysqli_set_charset($conn, “utf8mb4”);
$sql = ‘SELECT * from mytable’;
mysqli_select_db($conn,’test’);
$retval = mysqli_query($conn,$sql);
if (!$retval) {
die(‘Could not get data: ‘ . mysql_error());
}
while ($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) {
echo “ID :{$row[‘id’]} : Message: {$row[‘message’]} <br>” ;
}
echo “Fetched data successfully\n”;
mysqli_close($conn);
?>