mysql automatically cast strings to integer

前端 未结 3 1620
青春惊慌失措
青春惊慌失措 2021-01-13 05:52

I\'ve just noticed that if I do a MySQL request like this one:

SELECT 1 FROM myTable WHERE id = \'asdf\'

Then the string \'asdf\' is casted

3条回答
  •  迷失自我
    2021-01-13 06:15

    You must first sanitize your inputs via PHP.

    $id = 'asdf';
    if(is_numeric($id)){
        $query("SELECT 1 FROM myTable WHERE id = $id");
    }else{
        die("ID is not numeric");
    }
    

    Or you can do:

        SELECT 1 FROM myTable WHERE id = 'asdf' AND 'asdf' REGEXP '^-?[0-9]+$'
    

    This would cause the regex to = false, causing no rows to return.

提交回复
热议问题