我正在从xls文件将一些数据导入mysql表。
在数据上,我想在将其插入sql表之前使用mysqli_real_escape_string函数。
我的问题是:我应该在下面的代码中将array_map与escape函数放在哪里?
感谢您的帮助。
if(isset($_POST['submitButton']))
{
if($_FILES['file']['size'] != 0 )
{
if($_FILES["file"]["size"] > 5242880 ) { $error[] = "A fájl mérete maximum 5 MB lehet."; }
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $fajl_types)) { $error[] = "Nem engedélyezett fájl típus."; }
if(count($error) == 0 )
{
$path = "../imports/" . date( "Y-m-d" ) . '-' . rand(1, 9999) . '-' . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $path ))
{
$file_name = basename($path);
$objPHPExcel = PHPExcel_IOFactory::load('../imports/'.$file_name);
$dataArr = array();
foreach($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$dataArr[$row][$col] = $val;
}
}
}
unset($dataArr[1]); // since in our example the first row is the header and not the actual data
$user_pass = "";
$user_reg_date = date("Y-m-d-H:i:s");
$user_last_login = "";
$user_aktivation = "";
$user_vevocsoport = (int)0;
$user_newpass = "";
$user_imported = (int)1;
foreach($dataArr as $val)
{
$sql = "INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
'".$val['0']."',
'".$val['1']."'
)";
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}
}
else
{
$error[] = "A fájl feltöltése nem sikerült.";
}
}
}
else
{
$error[] = "Nem választott ki fájlt.";
}
}
答案 0 :(得分:0)
您可以在构建查询时添加它。像这样,转义和构建查询(它们彼此相关)在代码中彼此接近。
foreach($dataArr as $val)
{
$escapedVals = array_map(function($value) use ($kapcs) {
return mysqli_real_escape_string($kapcs, $value);
}, array_slice($val, 0, 2));
$sql = 'INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
"' . implode ('","', $escapedVals) . '"
)';
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}