当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Encoding issue with MySQLi

问题描述:

I have a MySQL table which I set to use the encoding utf8_swedish_ci. Two example values are 2 Kung and 1 Krön - note the swedish character. I need to search on these internationalized strings from within a PHP script. My PHP file is encoded in UTF-8. My code, with error handling stripped for clarity, looks like this:

$db = new mysqli($host, $user, $password, $user);

$db->set_charset('UTF-8');

$stm = $db->prepare('SELECT `id` FROM `myTable` WHERE `bok` LIKE ?');

echo "Searching on $value'...";

$stm->bind_param('s', $value);

$stm->execute();

$stm->bind_result($result);

$stm->close();

echo "Fetched '$result'.";

Now if I set $value to the first example value, I get the single matching row. With the other example value I get no rows. I have tested the queries to work in PHPMyAdmin. I figure the error lies with the international character and therefore that I messed up the encodings somewhere. So what did I do wrong and how do I fix this?

Edit: the line $db->set_charset('UTF-8'); fails because I used an incorrect charset. It should be utf8. Turns out I had too little error handling, I should've checked $db->error after set_charset.

网友答案:
$db->set_charset('UTF-8');

Note that MySQL is particular, the name it uses internally for the UTF-8 character set is utf8 (without dash), not the regular UTF-8.

In case of doubt, refer to SHOW CHARACTER SET; ;)

网友答案:

Try this, it might help.

$db = new mysqli($host, $user, $password, $user);
$db->set_charset('UTF-8');
$stm = $db->prepare('SELECT `id` FROM `myTable` WHERE `bok` LIKE ?');
$value = '%'.$value.'%'; //added this line
$stm->bind_param('s', $value);
$stm->execute();
$stm->bind_result($result);
$stm->close();
echo "Fetched '$result'.";

I tried LIKE '' with UTF-8 chars on a char(180) column with utf8_general_ci encoding and it returned 0 rows so I tried it with LIKE %''% and that worked

分享给朋友:
您可能感兴趣的文章:
随机阅读: