Home >Backend Development >PHP Tutorial >How to use PHP and UniApp to implement batch import of data
How to use PHP and UniApp to implement batch import of data
Importing data is one of the problems often encountered in daily development. By combining PHP and UniApp, we can easily implement the batch import function of data. In this article, I will introduce the specific implementation steps and provide corresponding code examples.
<?php // 连接数据库 $conn = new mysqli("localhost", "username", "password", "database_name"); // 处理上传文件 $file = $_FILES['file']; $temp = $file['tmp_name']; $filename = $file['name']; // 打开上传文件并读取数据 $handle = fopen($temp, "r"); $data = fgetcsv($handle); // 导入数据 while (($data = fgetcsv($handle)) !== false) { $name = $data[0]; $age = $data[1]; $email = $data[2]; // 将数据插入数据库 mysqli_query($conn, "INSERT INTO `table_name` (`name`, `age`, `email`) VALUES ('$name', $age, '$email')"); } // 关闭文件处理器 fclose($handle); // 关闭数据库连接 mysqli_close($conn); // 返回导入成功信息 echo "数据导入成功"; ?>
<template> <view> <input type="file" @change="handleUpload" /> <button @click="importData">导入数据</button> </view> </template> <script> export default { methods: { handleUpload(event) { this.file = event.target.files[0]; }, importData() { let formData = new FormData(); formData.append('file', this.file); // 调用后端API导入数据 uni.request({ url: 'http://localhost/import.php', method: 'POST', data: formData, success(res) { console.log('数据导入成功'); uni.showToast({ title: '数据导入成功', icon: 'success', duration: 2000 }); }, fail(res) { console.log('数据导入失败'); uni.showToast({ title: '数据导入失败', icon: 'none', duration: 2000 }); } }); } } } </script>
Summary
Through the above steps, we can easily use PHP and UniApp to import data in batches. Applying this function to specific projects can greatly improve development efficiency and user experience. I hope this article is helpful to everyone, thank you for reading!
The above is the detailed content of How to use PHP and UniApp to implement batch import of data. For more information, please follow other related articles on the PHP Chinese website!