0

I am new to php. I just got to know about sql injection, and have been thinking of ways to avoid it. One way I could think of is this: If we could hash the username, the password and other details before querying, then we can avoid sql injection completely. So is there a good way to do this? I mean, can we use a hash function to prevent sql injection?

The languages I am familiar with are C and C++. Is there a way to obtain the hex coding of each character entered in the string so that it can be converted to some other type before querying?

Sreram
  • 491
  • 1
  • 9
  • 22
  • you're looking at it wrong. there's nothing magical about usernames/passwords that make them a good conduit for sql injection. **ANY** data being inserted into a query string that comes from "outside" (including other data retrieved from the very same db) can cause injection problems. – Marc B Nov 12 '15 at 18:40

2 Answers2

4

I just got to know about sql injection

You don't have to manipulate your data in order to make it secure, you just have to use the proper methods with prepare statements.

For example, with PDO you can simply do

$result = $db->prepare($query);
$result->execute($array_data);

You can see more here http://php.net/manual/en/pdo.prepare.php, avoid to make your own functions it could lead to unexpected critical bugs.

Sam
  • 2,950
  • 1
  • 18
  • 26
  • From the linked page: "For example, you cannot bind multiple values to a single parameter in the IN() clause of an SQL statement." This makes filling the right side of `WHERE username IN (...)` more difficult. – Damian Yerrick Nov 12 '15 at 18:42
2

use PDO prepare to prevent your database from any kind of SQL Injection.

From the PDO::prepare

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37