It's necessary because mysql_query
is, in software terms, an ancient artifact. It's the Model T of MySQL database interfaces, clunky, unreliable, and downright dangerous if not used exactly as you should. If you're not extremely careful you will make a mistake, and even a tiny mistake will not go un-noticed if someone uses an automatic SQL injection bug detection tool on your site.
Basically you're living on borrowed time with mysql_query
.
If you use mysqli
or PDO and are diligent about using placeholders then the risk of a SQL injection bug is very low. It may take about half an hour to figure out how to convert your old code to these new methods, there really isn't a steep learning curve, and that knowledge will save you a lot of trouble in the future. Converting existing code usually isn't too big a deal if you use mysqli
and basic placeholders. I bet you even find some serious bugs while patching things up.
In terms of benefits, you won't need to make any mysql_real_escape_string
calls, you can just use bind_param
, and you won't have to worry about missing an escape on one of your variables. It's actually a lot less work in the long-run.
Additionally, using ?
or a named placeholder like :id
makes your queries significantly easier to read, debug and maintain. Further, you can use the same statement repeatedly and bind different values to it, ultimately making your application faster.
It is possible to write safe code with mysql_query
but why would you? The interface is listed as deprecated, which is the preliminary stage to it being removed from PHP entirely. If you want a future-proof application, it's best to use one of the supported interfaces.