prepared statements - are they necessary

后端 未结 2 793
有刺的猬
有刺的猬 2020-12-03 20:08

Prepared statments add a significant amount of code...yet I keep hearing mentions to use them...what value is added by going from 1 line of code to about 6? Is this simply

相关标签:
2条回答
  • 2020-12-03 20:26

    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));
    
    0 讨论(0)
  • 2020-12-03 20:41

    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:

    1. 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)
    2. 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.

    0 讨论(0)
提交回复
热议问题