When should I use prepared statements?

后端 未结 4 1313
感动是毒
感动是毒 2020-11-22 05:22

Originally I used mysql_connect and mysql_query to do things. Then I learned of SQL injection, so I am trying to learn how to use prepared statemen

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 05:58

    TL;DR Use prepared statements 100% of the time if your app accepts any user input


    You seem to have a slight confusion. First, please don't use mysql_*; the mysql_* functions are outdated, deprecated, and insecure. Use MySQLi or PDO instead. Second, mysql_num_rows has nothing to do with prepared statements and is not a PDO feature, anyway. You prepare the statement before you run the query, not after it when you want to count rows.

    As for when to prepare statements, @Mike'Pomax'Kamermans nailed it in the comments. If you ever, even once, use any data that has ever been touched by a user -- even a supposedly trusted user -- or is generated by any kind of third party or third-party application, including a browser, use prepared statements. Only if 100% of your data is hard-coded or generated entirely by your code (like a simple counter variable) can you trust it.

    For example, you cannot trust:

    • Usernames
    • Passwords
    • Email addresses
    • User comments
    • Phone numbers
    • Dates
    • Search strings
    • Browser client strings
    • Credit card numbers
    • File names for uploads
    • And any other kind of input created by a user or that a user could manipulate.

    You should validate all of these (for example, check that an email address is really an email address) before putting them in a database, of course. But even then, using prepared statements is the safe way to go.

提交回复
热议问题