I'm using PDO, and my $_POST['arraywithdata']
is an array filed with numeric values. I think that this is not enough secure, I just 开发者_如何学Cwan't to be sure and prevent myself from a hack.
This is my code:
$arr = $_POST['arraywithdata'];
$SQL->query("UPDATE `data_s` SET `set` = 1 WHERE `id` IN " . implode(", ", $arr));
As you can see, I'm not checking if the post code in a int or something.
Should I rather use something like:
implode(", ", (int) $arr)
?
I guess the above will not work, since array can not be an integer.
You need to convert each value of the array and not the array itself. You can use array_map
to do so:
implode(", ", array_map('intval', $arr))
Here array_map
will apply intval
to each value of $arr
and return a new array with the return values.
But as you’re using PDO, you might also be interested in a PDO solution.
It sounds like a bit of a messy way to pass an array to your script, if I were you I'd do the following:
<input name="test[]" value="arrayitem1" type="text" />
<input name="test[]" value="arrayitem2" type="text" />
Then in the PHP you can either loop through the data using a foreach look and checking is_int
or use array_map
with intval
and then explode
the data.
Recently, i faced this problem Here is what i did Hope this help
$arr = array(20,40,50);
$query[] = "UPDATE `data_s` SET `set` = 1 WHERE `id` IN (";
$count = count($arr);
foreach($arr as $v)
{
$query[] = (int)$v;
if ($count > 1)
{
$sql[] =",";
}
$count--;
}
$query[] = ")";
$query = implode("\n", $query);
$SQL->query($query);
IT will give you query like this
"UPDATE
data_sSET
set= 1 WHERE
idIN (20,40,50)"
;
精彩评论