开发者

Sanitizing An Array

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, lna开发者_如何转开发me, rank)
   VALUES ";
    $fname = count(fname);
    for($i=0; $i<$employee_count; $i++) {
    $query .= "(NOW(),'$department','{$fname[$i]}','{$lname[$i]}','{$rank[$i]}'),\n";
  }

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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜