Hướng dẫn like binary mysql

Hôm nay được chị tester thông báo 1 bug: Khi user login thì hệ thống không phân biệt username & password dạng chữ hoa, chữ thường 😐

Câu query chỉ đơn giản là:

SELECT user_login	
FROM sys_user 
WHERE user_login = '$user_login' 
          AND user_passwd = '$password'

Hóa ra thằng MySQL nó không phân biệt chữ hoa, chữ thường nếu field type là varchar :-s

Cách fix: Có nhiều cách nhưng đơn giản nhất là “ép” về dạng binary để so sánh theo byte

SELECT user_login	
FROM sys_user 
WHERE BINARY user_login = '$user_login' 
          AND BINARY user_passwd = '$password'

Nguồn: //dev.mysql.com/doc/refman/5.0/en/cast-functions.html#operator_binary

B.3.4.1 Case Sensitivity in String Searches

For nonbinary strings [CHAR, VARCHAR, TEXT], string searches use the collation of the comparison operands. For binary strings [BINARY, VARBINARY, BLOB], comparisons use the numeric values of the bytes in the operands; this means that for alphabetic characters, comparisons are case-sensitive.

A comparison between a nonbinary string and binary string is treated as a comparison of binary strings.

Simple comparison operations [>=, >, =,

Chủ Đề