Question: I want to upgrade and make more systematic, my protection against sql injection attacks. I gather the three main methods are pdo, prepared statements and mysql\_escape\_string, that pdo is considered best but mysql\_escape\_string considered adequate if you are meticulous. I don't think I am ready to go to PDO or prepared statements as I have a lot of complicated queries involving multiple tables so this would be a huge task. But I want to make use of mysql\_escape\_string more programmatic.

Rather than escape every individual variable that users submit, I was thinking of escape the SQL commands with a standard function that might require some modification to handle punctuation Is this a sound approach or will escaping the whole query create problems-I do use apostrophes, backticks and %, for example. It would seem that a standard function for every sql statement would be more systematic and standard than the variable by variable approach. So question is what modifications to handle punctuation might be needed? Also, is there anything else that ought to go into the function such as htmlspecialchars and strip\_tags as I gather mysql\_escape\_string is not 100% complete? 

Here is basic function.

```
function safe($sql) {
$safesql = mysql_real_escape_string($sql);
return $safesql;
}

```

Answer: 
> 
> I don't think I am ready to go to PDO or prepared statements as I have a lot of complicated queries involving multiple tables so this would be a huge task.
> 
> 
> 

Huge? Perhaps. Worth the effort though.

> 
> will escaping the whole query create problems
> 
> 
> 

Yes. Your function will have no way of knowing if a piece of SQL is an injection attack or something you intended.

You have to escape *text* at the point where it is inserted into *SQL*. You can't insert text into SQL and then figure out which bit was SQL and which bit was text afterwards.

> 
> is there anything else that ought to go into the function such as htmlspecialchars and strip\_tags
> 
> 
> 

`strip_tags` throws data away. I wouldn't use it.

Both `strip_tags` and `htmlspecialchars` offer protection against unsafe data being inserted into an HTML document. Use them before inserting data into an HTML document, not before inserting data into SQL.
The only way to make it work with the whole query is if you write your own SQL parser, and even then, you must try to magically *see* which parts of the query is SQL injections. That's not possible so no, you cannot do this with the entire query at once.