简体   繁体   中英

Query special characters from mysql db

I am using PHP 7.1.8 and I am trying to query my db. However, the serialized arrays have special characters, which are shown as the following:

Find below an example of my code:

// connect to db
$dbname = $conf['dbName'];
$dbuser = $conf['user'];
$dbpass = $conf['pwd'];
$dbhost = $conf['host'];

// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

$arr = $conn->query("SELECT * FROM postmeta WHERE post_id = "100" and meta_key = 'val' LIMIT 1;")->fetch_assoc()["meta_value"];

When querying the database directly, I get the correct value for . See below my ``$arr`:

在此输入图像描述

This error results basically in that I cannot unserialize the data correctly.

Any suggestions how to fix this error?

I appreciate your replies!

The problem lies in collation. Your MySQL returns specific symbols (temperature symbol) that is not supported by your current encoding.

Try to execute this query right before your selects: set names 'utf8';

Also, if you're showing this data in some kind HTML response, don't forget to add charset=UTF-8 to your meta tag of Content-type .

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* change character set to utf8 */
if (!$conn->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $conn->error);
    exit();
} else {
    printf("Current character set: %s\n", $conn->character_set_name());
}
$arr = $conn->query("SELECT * FROM postmeta WHERE post_id = "100" and meta_key = 'val' LIMIT 1;")->fetch_assoc()["meta_value"];

Please check the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM