multiple INSERTS and keeping PDO prepared statement security

大兔子大兔子 提交于 2019-12-24 10:47:36

问题


I have the following piece of code which sends to each member of mya_users a mail (this is what INSERT into inbox does.

$query_write_mass = "SELECT id FROM mya_users ORDER by artist_real_address ASC";
$result_write_mass = $db->prepare($query_write_mass);
$result_write_mass->execute();
while ( list($receiver_id) = $result_write_mass->fetch(PDO::FETCH_BOTH) ) { 

   $stmt = $db->prepare
     ("INSERT INTO inbox(folder_id, sender_id, sender_type, receiver_id, 
       receiver_type, title, message_body, time, date, flag, spam) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $stmt->bindValue(1, 0, PDO::PARAM_INT);
        $stmt->bindValue(2, 0, PDO::PARAM_INT);
        $stmt->bindValue(3, 'x', PDO::PARAM_STR);
        $stmt->bindValue(4, $receiver_id, PDO::PARAM_INT);
        $stmt->bindValue(5, $receiver_type, PDO::PARAM_STR);
        $stmt->bindValue(6, $_POST['title'], PDO::PARAM_STR);
        $stmt->bindValue(7, $_POST['body'], PDO::PARAM_STR);
        $stmt->bindValue(8, date("G:i:s"), PDO::PARAM_STR);
        $stmt->bindValue(9, date("Y-m-d"), PDO::PARAM_STR);
        $stmt->bindValue(10, 'n', PDO::PARAM_STR);
        $stmt->bindValue(11, '', PDO::PARAM_STR);                                                                                                                                                                                                   

        $stmt->execute();   
 }

what I want is to keep the benefits of security and escaping of PDO prepared statements, BUT insert say 10 rows at a time, so if I have 40k inserts I would benefit of multiple value insert speed and keep the number of inserts low.

thanks


回答1:


First, let me assure you that constant value is perfectly secure. So, you can dramatically reduce the number of bound parameters in your code

INSERT INTO inbox(folder_id, sender_id, sender_type, receiver_id, 
   receiver_type, title, message_body, dt, flag, spam) 
   VALUES (0, 0, 'x', ?, ?, ?, ?, NOW(), 'n', '')");

I also combined two fields date and time into one dt, as there is no reason to have them separated, yet it can let us use shorter code.

And now you can turn to the next step - using INSERT .. SELECT approach

INSERT INTO inbox(folder_id, sender_id, sender_type, receiver_id, 
   receiver_type, title, message_body, dt, flag, spam) 
   SELECT 0, 0, 'x', id, ?, ?, ?, NOW(), 'n', ''
   FROM mya_users ORDER by artist_real_address ASC

and bind your data to only three remaining variables!



来源:https://stackoverflow.com/questions/18170365/multiple-inserts-and-keeping-pdo-prepared-statement-security

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