消毒阵列 [英] Sanitizing An Array
问题描述
我有一个动态生成的表格.最终用户将能够向数据库提交员工详细信息.因此,数组$ fname将包含所有名字,$ lname将包含所有姓氏.然后将数组插入到MySQL中,如下所示:
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]}'),\n";
}
这有效很好,直到我们遇到危险字符(例如单引号),例如MC'Mahon,这使查询失败.我不能使用许多常规函数,例如mysqli_real_escape_string(),因为这是一个数组. 有没有办法对数组进行清理,即逃避数组内的任何危险字符,以便在将每个数组推入数组进行循环之前先对每个数组进行清理,然后将每个数组拆分为字符串,然后输入到MySQL中?
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?
推荐答案
您可以在for
之前使用 array_map
环形.该函数将回调应用于数组的每个值.在这种情况下,回调将为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);
根据以下评论进行更新:
要在过程模式下使用mysqli_real_escape_string
,您需要传递链接",因此需要创建一个自定义函数:
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);
这篇关于消毒阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!