问题描述
我必须创建可以上传excel文件并转换为MysqL数据库的页面。问题是我想在用户导入 excel 文件(替换表中的数据)时更新整个表数据,而不是插入新数据。这是我的代码
<?PHP
if (isset($_POST["import"])) {
$allowedFileType = [
'application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
if (in_array($_FILES["file"]["type"],$allowedFileType)) {
$targetPath = 'uploads/' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'],$targetPath);
$Reader = new \PHPOffice\PHPSpreadsheet\Reader\Xlsx();
$spreadSheet = $Reader->load($targetPath);
$excelSheet = $spreadSheet->getActiveSheet();
$spreadSheetAry = $excelSheet->toArray();
// print_r($spreadSheetAry); exit;
$sheetCount = count($spreadSheetAry);
for ($i = 1; $i <= $sheetCount; $i++) {
$customer_note = "";
if (isset($spreadSheetAry[$i][0])) {
$customer_note = $MysqLi->real_escape_string($spreadSheetAry[$i][0]);
}
// echo 'customer_note === '.$customer_note."<br>";
$customer_username = "";
if (isset($spreadSheetAry[$i][1])) {
$customer_username = $MysqLi->real_escape_string($spreadSheetAry[$i][1]);
}
// echo 'customer_username === '.$customer_username."<br>";
$item_name = "";
if (isset($spreadSheetAry[$i][3])) {
$item_name = $MysqLi->real_escape_string($spreadSheetAry[$i][3]);
}
// echo 'item_name === '.$item_name."<br>";
$quantity = "";
if (isset($spreadSheetAry[$i][3])) {
$quantity = $MysqLi->real_escape_string($spreadSheetAry[$i][4]);
}
// echo 'quantity === '.$quantity."<br>";
if (
!empty($customer_username) || !empty($item_name)
|| !empty($quantity)
) {
$query = "INSERT INTO orders(customer_username,item_name,quantity,customer_note)
VALUES ('$customer_username','$item_name','$quantity','$customer_note')";
// echo 'query === '.$query; exit;
if ($MysqLi->query($query) === TRUE) {
$type = "success";
$message = "Excel Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
} else {
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
我必须创建可以上传excel文件并转换为MysqL数据库的页面。问题是我想在用户导入 excel 文件(替换表中的数据)时更新整个表数据,而不是插入新数据。 我应该怎么办?提前致谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)