douyanjing0822 2011-07-17 21:13
浏览 10
已采纳

消毒数组

I have a form that is generated dynamically. The end users will be able to submit employee details to the database. So array $fname will contain all first names, $lname all last names ect. The arrays are then inserted into MySQL like so:

   $query = "INSERT INTO workers (date_added, department,fname, lname, rank)
   VALUES ";
    $fname = count(fname);
    for($i=0; $i<$employee_count; $i++) {
    $query .= "(NOW(),'$department','{$fname[$i]}','{$lname[$i]}','{$rank[$i]}'),
";
  }

This works great until we have dangerous characters like single quotes e.g MC'Mahon, which makes the query to fail. I cannot use many normal functions such as mysqli_real_escape_string() since this is an array. Is there a way to sanitize the array i.e escape any dangerous characters inside the arrays so that I sanitize each array before pushing it into them for loop that splits each array into strings that are then entered into MySQL?

  • 写回答

1条回答 默认 最新

  • dongping1922 2011-07-17 21:19
    关注

    You could use array_map before your for loop. That function applies a callback to each value of the array. In this case, the callback would be mysqli_real_escape_string.

    $fname = array_map('mysqli_real_escape_string', $fname);
    $lname = array_map('mysqli_real_escape_string', $lname);
    $rank = array_map('mysqli_real_escape_string', $rank);
    

    Update based on comments below:

    To use mysqli_real_escape_string in procedural mode, you need to pass the "link" so you need to create a custom function:

    function array_map_callback($a)
    {
      global $dbc;
    
      return mysqli_real_escape_string($dbc, $a);
    }
    
    $fname = array_map('array_map_callback', $fname);
    $lname = array_map('array_map_callback', $lname);
    $rank = array_map('array_map_callback', $rank);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题