Test if string could be boolean PHP

后端 未结 8 1948
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 17:51

I\'m getting a string from a $_GET and I want to test if it could be a boolean, before I use it for a part of a mysql query. Is there a better way of doing it than:



        
8条回答
  •  孤独总比滥情好
    2021-02-20 18:28

    Your checkBool() is quite right, IMHO, though there's a problem with the resulting SQL code. You can use TRUE and FALSE, but you must be aware that they aren't strings:

    The constants TRUE and FALSE evaluate to 1 and 0, respectively. The constant names can be written in any lettercase.

    So where it says this:

    "SELECT * FROM my_table WHERE male='".$_GET['male']."'"
    

    ... it should say this:

    'SELECT * FROM my_table WHERE male='.$_GET['male']
    

    It'd feel better if checkBool() was actually convertToBool() and you would feed your query with its result value rather than the original $_GET, but your code is not really wrong.

    BTW, I'm assuming that you are using a BOOL column type. This is what the manual says:

    These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true

    Of course, it's up to you whether to use BOOL, ENUM, CHAR(1) or anything else, as well as whether to accept 33 as synonym for TRUE ;-)

提交回复
热议问题