Search code examples
phpmysqlmysql-real-escape-string

Is it safe to cast as int instead of mysql_real_escape_string


Just wondering, my application needs to be as fast as possible and the variables already get cast as int, so I don't want to escape the string as well if it can be avoided.

Example is:

$var1 = (int)$_POST['number1'] //User input;
mysql_query("INSERT INTO ... $var1 ..");

Is that safe in all circumstances or should I also mysql_real_escape_string $var1 aswell?

Sometimes I also md5() vars instead of escaping them, but I imagine that's ok.


Solution

  • Yes, this will be safe with the caveat that any value that is not a valid integer will be cast to 0, which may cause side effects.

    As minitech says, using prepared statements really should be the way to go, as you won't have to worry about this at all any more.

    However, and more importantly, performance is not really an issue here and it's not worth thinking about. Whether you escape or don't escape a string will not influence your application's performance one bit (at least not if it's not megabytes big). Premature optimization is often a waste of time - such "optimizations" will only make the code harder to read and understand, which is much more important in the long run.