数据库配置(dbconfig.php)
“dbconfig.php”用于连接数据库。
指定数据库主机('$dbhost'),用户名('$dbusame'),密码('$dbpassword'),以及根据mysql数据库凭据的名称('$dbname')。
<?php //Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "onitroad"; //Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); //Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
创建数据库表
要存储成员的数据,需要在数据库中创建表。
以下SQL使用MySQL数据库中的某些基本字段创建“成员”表。
CREATE TABLE `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, `status` enum('Active','Inactive') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Active', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
将数据导出到CSV(ExportData.php)
导出Data.php文件使用PHP和MySQL处理数据导出过程。
- 从数据库中获取记录。
- 使用PHP Fopen()函数创建并打开具有仅写入模式的文件。
- 将标题列,格式为CSV,并使用PHP FputCSv()函数将其写入打开的文件。
- 从数据库的输出数据,格式为CSV并将其写入文件。
- 强制浏览器将数据作为CSV格式下载到文件中。
<?php //Load the database configuration file include_once 'dbConfig.php'; $filename = "members_" . date('Y-m-d') . ".csv"; $delimiter = ","; //Create a file pointer $f = fopen('php://memory', 'w'); //Set column headers $fields = array('ID', 'Name', 'Email', 'Phone', 'Created', 'Status'); fputcsv($f, $fields, $delimiter); //Get records from the database $result = $db->query("SELECT * FROM members ORDER BY id DESC"); if($result->num_rows > 0){ //Output each row of the data, format line as csv and write to file pointer while($row = $result->fetch_assoc()){ $lineData = array($row['id'], $row['name'], $row['email'], $row['phone'], $row['created'], $row['status']); fputcsv($f, $lineData, $delimiter); } } //Move back to beginning of file fseek($f, 0); //Set headers to download file rather than displayed header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="' . $filename . '";'); //Output all remaining data on a file pointer fpassthru($f); //Exit from file exit();
CSV文件格式
基于数据库表结构,CSV文件应具有这些字段名称,电子邮件,电话和状态。
要在数据库中导入CSV文件数据,CSV文件格式将类似于以下屏幕。
当数据导出到CSV文件时,下载的格式将看起来像以下屏幕。
导入和导出功能对数据管理部分非常有用。
导入功能允许用户在数据库中上传和插入多个数据。
使用导入功能,可以单击“数据库”中插入批量数据。
导出功能允许用户下载表数据列表并保存在文件中以用于脱机使用。
使用导出功能,可以以文件格式下载多个记录。
其中,CSV文件格式用于导入和导出Web应用程序中的数据。
CSV(逗号分隔值)文件以纯文本格式存储数据,并有助于在程序之间移动数据。
使用PHP和MySQL可以轻松地使用CSV文件实现导入和导出功能。
将数据库/导出数据导入数据库/导出数据到CSV文件都可以与PHP和MySQL集成。
在本教程中,我们将展示如何使用PHP和MySQL在数据库中导入和导出CSV文件数据。
在示例导入和导出脚本中,将实现以下功能。
- 从数据库中获取成员的数据并在网页中列出。
- 使用PHP将CSV文件数据导入MySQL数据库。
- 使用PHP和MySQL将数据导出到CSV。
CSV文件上传和下载(index.php)
最初,会员的数据在HTML表中列出了导入和导出选项。
- 现有成员数据从数据库中获取,并以表格格式列出。
- 导入按钮位于列表的顶部。
- 通过单击“导入”按钮,将出现“CSV文件上传”表单。
- 在提交时,表单被提交到“ImportData.php”文件中,用于将CSV文件数据导入数据库。
- FormToggle() - 此JavaScript函数用于显示/隐藏CSV上传表单,并在单击导入按钮时触发。
- 如果已提交的CSV文件导入请求,则从URL检索状态消息,并且在网页上显示导入状态。
- 导出按钮放在列表顶部。
- 导出链接导航到“exportdata.php”文件,以将表数据导出到CSV文件。
<?php //Load the database configuration file include_once 'dbConfig.php'; //Get status message if(!empty($_GET['status'])){ switch($_GET['status']){ case 'succ': $statusType = 'alert-success'; $statusMsg = 'Members data has been imported successfully.'; break; case 'err': $statusType = 'alert-danger'; $statusMsg = 'Some problem occurred, please try again.'; break; case 'invalid_file': $statusType = 'alert-danger'; $statusMsg = 'Please upload a valid CSV file.'; break; default: $statusType = ''; $statusMsg = ''; } } ?> <!-- Display status message --> <?php if(!empty($statusMsg)){ ?> <div class="col-xs-12"> <div class="alert <?php echo $statusType; ?>"><?php echo $statusMsg; ?></div> </div> <?php } ?> <div class="row"> <!-- Import & Export link --> <div class="col-md-12 head"> <div class="float-right"> <a href="javascript:void(0);" class="btn btn-success" onclick="formToggle('importFrm');"><i class="plus"></i> Import</a> <a href="exportData.php" class="btn btn-primary"><i class="exp"></i> Export</a> </div> </div> <!-- CSV file upload form --> <div class="col-md-12" id="importFrm" style="display: none;"> <form action="importData.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" class="btn btn-primary" name="importSubmit" value="IMPORT"> </form> </div> <!-- Data list table --> <table class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th>#ID</th> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Status</th> </tr> </thead> <tbody> <?php //Get member rows $result = $db->query("SELECT * FROM members ORDER BY id DESC"); if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['phone']; ?></td> <td><?php echo $row['status']; ?></td> </tr> <?php } }else{ ?> <tr><td colspan="5">No member(s) found...</td></tr> <?php } ?> </tbody> </table> </div> <!-- Show/hide CSV upload form --> <script> function formToggle(ID){ var element = document.getElementById(ID); if(element.style.display === "none"){ element.style.display = "block"; }else{ element.style.display = "none"; } } </script>
此示例代码使用Bootstrap 4库来样式调整HTML表,表单和链接。
如果我们不想使用Bootstrap结构,我们可以省略其中。
否则,包括引导库文件和自定义样式表文件(如果有的话)。
<!-- Bootstrap library --> <link rel="stylesheet" href="assets/bootstrap/bootstrap.min.css"> <!-- Stylesheet file --> <link rel="stylesheet" href="assets/css/style.css">
将CSV数据导入数据库(ImportData.php)
“importData.php”文件将CSV文件上传和数据导入进程与PHP和MySQL处理。
- 验证提交的文件是否有效的CSV文件。
- 使用php is_uploaded_file()函数检查CSV文件上传状态。
- 使用PHP Fopen()函数打开CSV文件。
- 使用PHP FGETCSV()函数从CSV文件解析数据。
- 根据会员的电子邮件将数据插入或者更新到数据库中。
<?php //Load the database configuration file include_once 'dbConfig.php'; if(isset($_POST['importSubmit'])){ //Allowed mime types $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'); //Validate whether selected file is a CSV file if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){ //If the file is uploaded if(is_uploaded_file($_FILES['file']['tmp_name'])){ //Open uploaded CSV file with read-only mode $csvFile = fopen($_FILES['file']['tmp_name'], 'r'); //Skip the first line fgetcsv($csvFile); //Parse data from CSV file line by line while(($line = fgetcsv($csvFile)) !== FALSE){ //Get row data $name = $line[0]; $email = $line[1]; $phone = $line[2]; $status = $line[3]; //Check whether member already exists in the database with the same email $prevQuery = "SELECT id FROM members WHERE email = '".$line[1]."'"; $prevResult = $db->query($prevQuery); if($prevResult->num_rows > 0){ //Update member data in the database $db->query("UPDATE members SET name = '".$name."', phone = '".$phone."', status = '".$status."', modified = NOW() WHERE email = '".$email."'"); }else{ //Insert member data in the database $db->query("INSERT INTO members (name, email, phone, created, modified, status) VALUES ('".$name."', '".$email."', '".$phone."', NOW(), NOW(), '".$status."')"); } } //Close opened CSV file fclose($csvFile); $qstring = '?status=succ'; }else{ $qstring = '?status=err'; } }else{ $qstring = '?status=invalid_file'; } } //Redirect to the listing page header("Location: index.php".$qstring);