0

I'm working with SQLite3 in PHP.

A friend told me that I should prefer prepared statements, and I read this in many posts here on StackOverflow too. I want to understand the benefits of using prepared statements because I have to write much more lines, than regular escaping like using:

$db->exec("Insert INTO table VALUES(NULL,'".$db->escapeString($value)."')"

or using:

foreach($_POST as $k => $v) {
    $_POST[$k] = $db->escapeString($v);
}

Why should I use prepared statements? What are the pros and cons?

halfer
  • 19,824
  • 17
  • 99
  • 186
mr_app
  • 1,292
  • 2
  • 16
  • 37
  • Possible duplicates: http://stackoverflow.com/q/14535337/472495, http://stackoverflow.com/q/8263371/472495, http://stackoverflow.com/q/5200238/472495 – halfer Mar 19 '13 at 11:32

2 Answers2

2

People often confuse parameters with native prepared statements. I doubt Sqlite supports the latter, but nevertheless you have to ALWAYS use parameters to substitute the actual data in the query.

When parameter (also called "placeholder") being processed, important things happen:

  • ALL the required formatting (i.e. escaping and quoting) applied (while escaping will do only half of the job - leaving your query wide open to injection).
  • such a formatting being applied to the very data that is going to the query, not to the source variable, spoiling it (so, you can send it via email or store in a session).
  • such a formatting being applied automatically, making your safety independent from the good will of developers. that's highly important matter
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

Prepared Statement is mostly used for avoiding SQL injection done by hackers and any malicious program.

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100