Can 'false' match some string in mysql?

前端 未结 4 594
夕颜
夕颜 2021-01-21 15:48

I have a table like this:

CREATE TABLE IF NOT EXISTS `session` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `token` varchar(32) NOT NULL,
  `profile` varchar(1000         


        
相关标签:
4条回答
  • 2021-01-21 16:14

    Is there any reason you're not testing token is null or token like ''? Comparing a varchar to false is a bad idea regardless of whether the DB will catch your mistake or not... a varchar is never false, and false doesn't equal null.

    0 讨论(0)
  • 2021-01-21 16:20

    This should be a comment, but I don't have enough reputation... so..

    DelphiQin, you said in a comment that you are passing the result of the CI "get()" method to the query parameter. I've been there and I solved by just casting the variable to string before passing to the query:

    (string)$my_var
    

    This way, it will use '' (empty string) instead of boolean false.

    I hope it helps people with the same problem.

    0 讨论(0)
  • 2021-01-21 16:21

    In MYSQL, FALSE is not a boolean value, it's an integer, more specifically zero. In fact, MySQL does not have boolean column types (it has BOOL and BOOLEAN but they're mere aliases for TINYINT). So your query is a synonym for:

    SELECT * FROM session WHERE token = 0
    

    Since token is a VARCHAR, MySQL needs to convert your strings to number. Run this query and you'll get an idea about the rules:

    SELECT
        0 + "0001",
        0 + "123abc",
        0 + "abc123"
    

    As a result, fa356333dd3ee8f1b18b8bf0a827e34c casts to 0 because it starts with a letter, thus the match.

    0 讨论(0)
  • 2021-01-21 16:23

    If you want to compare a boolean with a varchar, MySQL has to do some implicit type conversion. MySQL casts the varchar value to a boolean, checking only the first character.

    If the character is a character or number 0, then the string is evaluated to 0, thus False.
    If the character is a number different than 0, then the string is evaluted to 1, thus True (and not appearing in your result set)

    The only thing to do is not to compare a string with a boolean, because it makes no sense.

    0 讨论(0)
提交回复
热议问题