How can I prevent SQL injection in PHP?


WebTUTs 2.0

Today i will gonna show you how to prevent sql-injection in php.

sqlinject

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

Using PDO:

  1.     $stmt = $pdo->prepare(‘SELECT * FROM employees WHERE name = :name’);
  2.     $stmt->execute(array(‘:name’ => $name));
  3.     foreach ($stmt as $row) {
  4.         // do something with $row
  5.     }

Using mysqli:

  1.     $stmt = $dbConnection->prepare(‘SELECT * FROM employees WHERE name = ?’);
  2.     $stmt->bind_param(‘s’, $name);
  3.     $stmt->execute();
  4.     $result = $stmt->get_result();
  5.     while ($row = $result->fetch_assoc()) {
  6.         // do something with $row
  7.     }

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable…

View original post 429 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s