Is this evidence of a request injection?

I use PDO to talk to my database and I wonder if this type should be used

$dbh->query("SELECT * FROM recipes WHERE id=".(int)$id);

enough to prevent sql injection? In this case, $ id is always an integer.

I also wonder what would be a good way to prevent injection in this expression if the variable was a string.

+1
source share
6 answers

Yes. Casting to int prevents all the unpleasant features of SQL injection.

If the variable was a string, you should use prepared statements to pass it.

$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql);
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
+4
source

PDO, :

:

$dbh->prepare("SELECT * FROM recipes WHERE id = ?");
$dbh->bindParam(1, (int) $id);
// more code.....
+3

:

$dbh->query("SELECT * FROM `recipes` WHERE `id=`'".(int)$id."'");
0

$id , . ( ) ; PDO::quote.

0

, , SQL Injection, .

Automatic SQL Injection Tool, .

0

, PHP (int) NULL 0.

Therefore, if you had a significant relationship with identifier 0 in the application, this may inadvertently cause this value.

0
source

All Articles