0

I'm trying to make my queries safe to SQL injection and luckily, the variables that could be targeted are only integers or floats, so I was wondering if, in this case, it is enough to use sprintf() (not even using mysqli_real_escape_string()). I made a few tests, and to the moment it looks good, since it parses any input as a float/integer, so no SQL statement should be executed. Is there any way to hack this? It looks too easy and wonderful to me :D

Dhanesh Budhrani
  • 190
  • 3
  • 15
  • If all you're injecting into your sql is floats or ints and they are properly cast then yes, I would say this is safe. But why would you want to? Prepared statements with PDO don't just give you a safer app: they give you cleaner better code – jcbwlkr Apr 05 '13 at 10:50
  • @jacobwalker0814 actually, sprintf-based solution would be cleaner. – Your Common Sense Apr 05 '13 at 11:02
  • @YourCommonSense sure for particular queries (such as mentioned by the asker) it might be cleaner to just have the one line with variables cast. I'm stating that the feel of the overall app is cleaner with a database object like PDO. Of course this is a bit subjective and my opinion. – jcbwlkr Apr 05 '13 at 11:06

3 Answers3

1

Why don't you use prepared statements? They give a better protection fron SQL injection plus may improve query performance if they are reused.

Gevatter Tod
  • 131
  • 4
-2
$int = 125 . 'asda';
$float = 654.12;

function validateNumber($number) {
    if (strpos($number, '.')) {
        $number = floatval($number);
    } else { 
        $number = intval($number);
    }
    return $number;
}

echo validateNumber($int); // 125
echo '<br />';
echo validateNumber($float); // 654.12

Checking if number is int or float and returning their values.

dpitkevics
  • 1,238
  • 8
  • 12
-2

it is enough to use sprintf()

yes.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345