I was recently working on a pull request where I wanted to take an array of object IDs and convert that into a string to be used in a SQL statement.
But, to prevent potential issues such as SQL injection, I needed to find a way to sanitize the array of integers and make sure that we only had integers in the array. Here is the solution that I used.
// Sanitize so that the array only has integer values.
$sanitized_array = array_map( 'intval', $ids );
// Now that we have all integers in our array, we can safely implode the
// array to be used in a SQL statement.
$ids_string = implode( ', ', $sanitized_array );
$sql = "SELECT * FROM {$table} WHERE {$object_id_column} IN ( {$ids_string} ) AND meta_key = %s";
If you’re not used to mapping an array of values, you may be wondering what the heck array_map()
is doing. What array_map() does is iterate over an array (the second argument) and apply a callback function (the first argument) to each value in the array.
We then get back the resulting array with each value being sanitized by intval()
.
Alternative solution to sanitizing an array of integers
If you’re still a bit confused about what array_map( 'intval', $ids )
, here’s another way to approach the issue:
// Sanitize so that the array only has integer values.
$sanitized_array = array();
foreach( $ids as $id ) {
$sanitized_array[] = intval( $id );
}
// Now that we have all integers in our array, we can safely implode the
// array to be used in a SQL statement.
$ids_string = implode( ', ', $sanitized_array );
$sql = "SELECT * FROM {$table} WHERE {$object_id_column} IN ( {$ids_string} ) AND meta_key = %s";
In both examples, we iterate over the $ids
array and apply the intval()
function to each value.
Leave a Reply