Typecasting numeric ID to integer to prevent SQL-injection

蹲街弑〆低调 提交于 2019-12-12 13:54:55

问题


I'm implementing a bulk delete feature. The application uses PDO, but I haven't figured out a nice way to use prepared statements for this.

I have an array of ID's of rows to delete, any length:

array(3, 5, 8, [...])

With prepared statements I'd have to create a string of questions marks to use as a placeholder, and then bind the values, looking something like this:

$question_marks = array();
foreach($ids) $question_marks[] = '?';
$question_marks = join(', ', $question_marks);

$statement = $pdo->prepare('DELETE FROM `table` WHERE `id` IN ('.$question_marks.')');

for($i = 0; $i < count($ids); $i++) {
    $statement->bindValue($i + 1, $ids[$i]);
}

$statement->execute();

What I had in mind would be typecasting the ID's into integer, so that any SQL-injection would be removed, which is my question: would it?

$id_string = array();
foreach($ids as $id) $id_string[] = (int) $id;
$id_string = join(', ', $id_string);

$statement = $pdo->prepare('DELETE FROM `table` WHERE `id` IN ('.$id_string.')');

$statement->execute();

It's still a bit hacky, but in my opinion much nicer than the previous solution.

Is this safe? Are there any alternative solutions?

来源:https://stackoverflow.com/questions/15620207/typecasting-numeric-id-to-integer-to-prevent-sql-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!