I have a couple of basic questions on parametrized queries
Consider this code:
$id = (int)$_GET['id'];
mysql_query("UPDATE table SET field=1 WHERE id=".$id);
Now the same thing using a parametrized query
$sql = "UPDATE table SET field=1 WHERE id=?";
$q = $db->prepare($sql);
$q->execute(array($_GET['id']));
My questions are:
- is there any situation where the first code (i.e. with the
(int)cast) is unsafe? - is the second piece of code OK or should I also cast
$_GET['id']to int? - is there any known vulnerability of the second piece of code? That is, is there any way an SQL attack can be made if I am using the second query?
is there any situation where the first code (i.e. with the (int) cast) is unsafe?
I’m not a PHP expert, but I think there shouldn’t be. That’s not to say that PHP doesn’t have bugs (either known or yet to be discovered) that could be exploited here.
is the second piece of code OK or should I also cast $_GET[‘id’] to int?
Likewise, the second piece of code should be absolutely fine – even if the data type was a string, MySQL would know not to evaluate it for SQL as it’s a parameter and therefore only to be treated as a literal value. However, there’s certainly no harm in also performing the cast (which would avoid any flaws in MySQL’s handling of parameters) – I’d recommend doing both.
EDIT – @Tomalak makes a very good point about cast potentially resulting in incorrect data and suggests first verifying your inputs with sanity checks such as
is_numeric(); I agree wholeheartedly.is there any known vulnerability of the second piece of code? That is, is there any way an SQL attack can be made if I am using the second query?
Not to my knowledge.