问题
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