Quick Tip: Save time on escaping from mysql_real_escape_string()

All data should be escaped before going into a query, to prevent a SQL-injection attack. The current “best practice” is to use mysql_real_escape_string(), which connects to the DB, checks how strings should be escaped, and then returns the safe string.

Unfortunately, this requires a round trip to the DB, and it takes time and resources. Here’s a trick to make things faster.

If the data you’re escaping is supposed to be an integer, and not a string, you can do this:

$_data = (int)$data;

This will force the value to be an integer. There’s no way to do an SQL-injection with a number alone, and this is something that gets done very quickly (as compared to the mysql_real_escape_string).

1 thought on “Quick Tip: Save time on escaping from mysql_real_escape_string()”

Leave a Reply