ebol4
ebol4

Reputation: 152

Converting from mysql_query's to prepared statements (mysqli/PDO)? Necessary?

I have been learning PHP and MySQL over the last few weeks, and I'm just now hearing about prepared statements and PDO/mysqli. I did some reading and people are saying that stuff like:

$getFromDatabase = mysql_query("SELECT * FROM table WHERE userid='$id'");
while($row = mysql_fetch_assoc($getFromDatabase)){
    stuff();
}

...won't work anymore. I use stuff like that pretty frequently in my code. I also am reading a lot about how prepared statements are much better protection against injection. I've got a thorough understanding of how it is better, but is it so much better that it's worth switching away from mysql_real_escape_string()? Is it necessary to switch to Mysqli or PDO? In what situation could mysql_real_escape_string() be bypassed where a prepared statement couldn't?

Upvotes: 2

Views: 2160

Answers (1)

tadman
tadman

Reputation: 211560

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.

Upvotes: 7

Related Questions