Question

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.

Was it helpful?

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.

OTHER TIPS

Yes, it's safe in all circumstances, although you'd probably want to check if $_POST['number1'] is a valid integer, too, to avoid notices.

And, even though you said

I'm only wondering about safeness, not too worried about prefered [sic] methods and coding standards.

I will still recommend that you use prepared statements.

As minitech said good practice is to also make sure you are checking that it is an integer. It really would be more secure to use prepared statements though, i recently took up to PDO and wouldn't go back.

It is safe but bear in mind that any string will be cast to 0, not null or anything like that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top