Understanding PDO Prepared Statements and Binding Parameters

后端 未结 1 667
無奈伤痛
無奈伤痛 2021-01-17 03:52

From experience and also having been told constantly the benefits of using prepared statements and binding my parameters, I have constantly used those two techniques in my c

相关标签:
1条回答
  • 2021-01-17 04:04

    You're correct that the first case is insecure. It's important to understand though, that preparing a statement only has value if you are using variable data, and/or executing the same query repeatedly. If you are executing plain statements with no variables, you could simply do this:

    $sql = "SELECT * from myTable WHERE this_column IS NOT NULL";
    $result = $conn->query($sql);
    

    And end up with a PDOStatement object to work with, just like when you use PDO::exec().

    For your second case, again, you're largely correct. What's happening is the variable passed to the database is escaped and quoted (unless you specify otherwise with the third argument to PDOStatement::bindParam(), it's sent as a string which is fine for most cases.) So, the query won't "fail" if bad data is sent. It behaves exactly as if you had passed a valid number that didn't exist as an ID in the database. There are, of course, some edge cases where you are still vulnerable even with a correctly prepared statement.

    Also, to make life easier, you can use prepared statements like this, to do implicit binding:

    $sql = "SELECT * FROM myTable WHERE id = :id";
    $stmt = $conn->prepare($sql);
    $stmt->execute([":id"=>$id]);
    

    Or even like this, with un-named parameters:

    $sql = "SELECT * FROM myTable WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$id]);
    

    Naturally, most of this has been explained in the comments while I was typing up the answer!

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