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
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:
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.