I know that this question may be closed by some of you, but my question came up from you and your answers. I am reading the past two hours questions and answers for SQL Inje
Prepared statements don't. Bound parameters secure the statement (not the database as a whole) so long as all your untrusted data is passed via a parameter rather than being interpolated into the statement. When people use prepared statements, they almost always use bound parameters too, so the two names are often conflated.
mysql_real_escape_string
almost always does the job, but since it adds additional steps to the process, it is more prone to human error.
There are certain instances when prepared statements cannot be used. For example, when you must dynamically generate the contents of an IN()
clause, you cannot do WHERE col IN (?)
if you have dynamically chosen the comma-separated values to go into the IN()
. Also, if you need to dynamically generate the columns list in your SELECT
clause, you must do it by building up the SQL string.
Bottom line is, both have their place. Prepared statements are excellent for predetermined queries, or queries that must be executed multiple times. Escaped dynamic SQL is excellent when 1) you must have maximum flexibility and 2) you don't forget to escape all your input.
This is a good discussion. Your question assumes there is one technique that will "secure your database". In fact, there is no single technique that is best for all cases. So you need to learn to use multiple solutions in different situations.
See my presentation SQL Injection Myths and Fallacies where I give details on everything you need to know to defend against SQL injection.
I also cover SQL injection in my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming.
Both. Prepared statements will protect you against SQL injections if, and only if, you use them in a correct manner. Just' using' prepared statements won't help if you're still interpolating variables for table/column names for example.
$stmt = "SELECT * FROM $table WHERE $column = ?"; //not good...