code (newbie):
if(isset($_POST['selection']))
{
include_once 'pdo_init.php';
$params_str = str_repeat('?,',count($_POST['selection']));
$params_str = substr($params_str,0,-1);
$res = $pdo->prepare('DELETE FROM funcionario WHERE codigo in ('.$params_str.')');
if($res->execute($_POST['selection']))
{
return json_encode(array(
'success' => 1,
'msg' => 'os registros foram deletados com sucesso!'
));
} else {
return json_encode(array(
'success' => 0,
'msg' => 'nao admitimos sql-injection aqui seu safado!'
));
}
} else {
# error out
break;
}
Pedantically, no it is not 100% safe (which you typically get from prepared statements in general). That's because with MySQL, PDO emulates prepared statements internally. This means that the data is escaped, so there is no benefit to using prepared statements over escaping when it comes to PDO (with the default settings at least).
You can change this by setting PDO::setAttribute(PDO::ATTR_EMULATE_PREPARES, 0)
on the connection.
MySQLi does use true prepared statements, so I would suggest using that instead.
Looks like you're dynamically making a parameterized query.
Parameterized queries are injection safe.
But remember to watch out for the content itself, too
It seems injection safe, as long as the user is allowed to delete all rows in the table (because she can send a POST with all codigo's in the table if she wants to).
It's not possible to trick your query into touching other tables.
You're doing it correctly using the ?
and prepare
. Note that the one situation that PDO will not protect you against is dynamic table/column names. PDO (and mysql_real_escape_string) will not esacape backticks, `, so try to never use dynamic table or column names.