Search code examples
phpmysqlsql-injection

Does is_numeric() mean a var is safe for MySQL?


Question says it all hopefully, if I check a variable returns true for is_numeric(), is it ok to put directly into the MySQL query, or do I need to apply standard escaping? I'm thinking null character, overflow exploits and stuff.

An ambiguous example would be:

if(is_numeric($_GET['user_id'])) {
    mysql_query("SELECT * FROM `users` WHERE id = ".$_GET['user_id']);
}

The datatype in MySQL is INT().


Solution

  • The safest way in my opinion is to convert the user_id to an integer, if it's invalid it will return 0.

    $user_id = (int) $_GET['user_id'];
    
    if ($user_id > 0) {
        mysql_query("SELECT * FROM `users` WHERE `id` = " . $user_id);
    }