mysqli prepared statement cannot read unicode

2019-08-06 18:31发布

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.

screenshot_1

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.

3条回答
戒情不戒烟
2楼-- · 2019-08-06 18:57

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楼-- · 2019-08-06 19:07

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');
查看更多
ゆ 、 Hurt°
4楼-- · 2019-08-06 19:07

This solved the problem:

iconv('windows-1250', 'utf-8', $EstablishmentName);
查看更多
登录 后发表回答