mysqli prepared statement cannot read unicode

懵懂的女人 提交于 2019-12-11 14:00:39

问题


Assume Adams’ Inn America’s Best Inn stored in the db table establishment

I have to check Adams’ Inn America’s Best Inn in a variable $EstablishmentName

$stmt = $sql->prepare("SELECT ID FROM `establishment` WHERE Name=? LIMIT 1");
$stmt->bind_param("s",$EstablishmentName);
$stmt->execute();
$stmt->store_result();
print $stmt->num_rows;

The problem is I can't find them.

OUTPUT 0

Note enclosed $EstablishmentName with mb_convert_string($EstablishmentName,'HTML-ENTITIES') else you'll end up with error Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='

UPDATE: I use set_charset('utf8') for the client side; the table charset is utf8, and collation is utf8_general_ci. The text is encoded as what the original text is. I am using the following DB Manager: SQLyog and PHPMyAdmin.

UPDATE #2: I have attached the screenshot for you to look that I am telling the correct charset.

I use $sql->set_charset('utf-8');

Array
(
    [BrandName] => America's Best Value Inn
    [try1] => 1
)

Array
(
    [BrandName] => Adams' Inn
    [try1] => 0
)

Array
(
    [BrandName] => Ambassador Inn and Suites
    [try1] => 1
)

Array
(
    [BrandName] => Amberley Suite Hotel
    [try1] => 1
)

Array
(
    [BrandName] => America's Best Value Inn
    [try1] => 0
)

UPDATE #3 Ok, sorry. The column Name was latin1_swedish_ci.
I have updated the column Name:

ALTER TABLE establishment MODIFY NAME VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_general_ci;

This should work without the mb_convert_string() now.


回答1:


Just put

mysqli_set_charset($db_connection, 'utf8');

after your database connection.

Example

$con=mysqli_connect("localhost", "root", "xxxxx","database");
mysqli_set_charset($con, 'utf8');



回答2:


The only thing I could tell that I see many confusions here

  • prepared statements are irrelevant here, as they implements only method of data substitution, but do not alter the data itself. You will have the same result adding value into database directly.
  • mb_convert_string cannot cause Illegal mix of collations error as this error is triggered by internal internal encodings conflict, not by the data format.
  • there is no code to proof that stored value is equal to one used to check

Assuming you can get Adams’ Inn America’s Best Inn value based on id, let me suggest you to retrieve it, and then compare manually. var_dump() them. If you still cannot see the difference - urlencode() them first




回答3:


This solved the problem:

iconv('windows-1250', 'utf-8', $EstablishmentName);


来源:https://stackoverflow.com/questions/14908446/mysqli-prepared-statement-cannot-read-unicode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!