Prepared statements add a significant amount of code...yet I keep hearing mentions of using them...what value is added by going from 1 line of code to about 6? Is this simply to protect against SQL injection?
php.net on prepared statements here
Prepared statements offer excellent protection against SQL injection.
In addition to SQL injection protection, prepared statements offer reduced load on the database server when the same query is to executed multiple times, such as in an INSERT
loop. The statement is only compiled once by the RDBMS rather than needing to be compiled each time as it would in a mysql_query()
call.
Different APIs require varying amounts of code to execute a prepared statement. I find that PDO can be a little less verbose than MySQLi, if for example your situation permits the use of implicit parameter binding inside the execute()
call. This only works, if all your params can be evaluated as strings though.
// PDO implicit binding example:
// Not many lines of code if the situation allows for it
$stmt = $pdo->prepare("SELECT * FROM tbl WHERE col1=? AND col2=? AND col3=?");
$stmt->execute(array($val1, $val2, $val3));
It's not fair to say that prepared statements cause 1 line of code to explode to 6. Actually, to use one you need just 2 lines: one to prepare the statement, and one to bind the parameters. Any other code you write (execute query, bind results, fetch results, etc.) would also be needed even if you didn't use prepared statements.
So in essence we are talking about what one additional line of code buys you. It buys you two things:
- Protection against sql injections (which also includes protection against non-malicious malformed queries, e.g. preventing your query from breaking if an injected variable contains a single quote)
- Possible performance benefits, if you end up executing the same prepared statement for different injected values.
Point #2 may not always apply, but consider that point #1 also saves you the necessary trouble of manually escaping the values to be injected in your query. This would be additional code (even if you can do it inline on the same line) that you would need to write yourself if not using prepared statements.
As I see things, we can conclude that with prepared statements you end up getting security and possibly performance for free.
精彩评论