7

In PHP, I've found a few methods to prevent Sql Injection. Binding parameters is one of them. But I'm unable to find a complete explanation of how binding parameters actually prevent Sql Injection. I was of the notion that binding parameters simply save time in binding different data to the same Sql statement. How does prevention of Sql injection come into picture?

Mithil Bhoras
  • 337
  • 5
  • 14
  • 4
    I recommend reading http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – MonkeyZeus May 25 '16 at 12:12
  • Here is a thorough explanation that is exactly addressing your confusion, [The Hitchhiker's Guide to SQL Injection prevention::Prepared statemens](https://phpdelusions.net/sql_injection#prepared) – Your Common Sense May 25 '16 at 12:32

1 Answers1

25

I think a simple example will explain you the thing:

  "select * from myTable where name = " + condition;

imagine that user input as a condition is

  '123'; delete from myTable; commit;

what happens then? the query executed will be

  select * from myTable where name = '123'; delete from myTable; commit;

or actually we have three queries with disastrous consequences:

  select * from myTable where name = '123';
  
  delete from myTable; 
  
  commit;

in case of bind variables

  "select * from myTable where name = @prmName"

whatever user input is it'll be one and only one query and the weird input above will always be treated as a string, not as a part of query. The outcome will be (most probably) an empty cursor, since there're no names within myTable like

  "'123'; delete from myTable; commit;"
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215