使用XAMPP和FPDF库的PHP批量操作
在处理动态数据库记录时,批量插入和批量输出是一些最有价值的功能。
当需要将Excel表或CSV中记录的数据添加到数据库中时,批量插入是合适的。
批量操作的好处
当数据库记录需要从一个单独的文件中检索时,批量导出效果很好。
例如,一家公司可能在库存报告中生成其销售额、雇员、每个产品的利润和资产。
这种情况意味着所有的数据库记录都是以一种特定的方式组织起来的,经过格式化,然后以一种可读的格式打印出来。
在处理动态数据库时,PHP开发人员应该了解批量导出和导入的概念。
这两种方法在进行系统检修或从一个系统迁移到另一个系统时很有帮助。
目标
本文将帮助读者了解如何在PHP中实现批量插入和批量导出。
我们将建立一个使用这两种功能的独特项目。
项目概述
我们将有一个简单的员工管理系统,支持批量插入和批量导出。
我们将把数据导出到Excel和PDF。注意,这个项目将使用MySQL数据库、PHP和Bootstrap。
先决条件
除了具备基本的Web开发技能外,读者应该对以下方面有所了解。
- 与MySQL数据库一起工作。
- PHP编程语言的基础知识。
- 使用Bootstrap 4。
- [XAMPP]。
项目设置
创建一个项目文件夹,名称由你选择。在这个文件夹中,添加以下组件。
- 一个名为
files的文件夹,用于存储从系统中导入的文件。 - 一个名为
Database.php的文件。它将包含我们所需操作的登录。 - 一个
index.php,将向用户展示信息或用户界面。
用户界面
我们将使用基本的bootstrap风格来定制我们的表格和按钮。
网络应用程序将有一个导航条和容器。它也将有一个表格,用于选择要导入数据库的文件类型。
<form method= "post" enctype = "multipart/form-data" class="form-inline my-2 my-lg-0">
<div class="sm-3">
<input class="form-control mr-sm-2" type="file" name="file">
<input type="submit" name= "submit" value="Import" class="btn btn-success my-2" style="background-color: #02a86b;">
</div>
</form>
表格中有两个按钮,用于将所有记录导出到Excel或PDF,如下图所示。
<form method= "post" class="form-inline my-2 my-lg-0">
<input type="submit" class="btn btn-primary my-2" name="excel" value="Export to excel"><hr>
<input type="submit" class="btn btn-primary my-2" name="pdf" value="Export to pdf">
</form>
我们也有一个表格,显示员工的姓名、部门和年龄的列表。
<thead>
<tr>
<th scope="col"></th>
<th scope="col">FIRST NAME</th>
<th scope="col">LAST NAME</th>
<th scope="col">DEPARTMENT</th>
<th scope="col">AGE</th>
</tr>
</thead>
<tbody>
$database->getRecords();
</tbody>
请注意,上述用户界面的代码是写在index.php 文件中的。
在index.php 文件中,我们需要include Database.php 文件并实例化Database 类。
<?php
include('Database.php');
$database = new Database();
在数据库类中工作
数据库类包含了应用程序的驱动代码。
它也有一个数据库类的构造函数,并强调了我们需要在系统上执行的各种功能。
在开始本节之前,在实例化的数据库类下面添加这些片段。
if(isset($_POST['submit'])){
$database->importFile($_FILES['file']['tmp_name']);
}
if(isset($_POST['excel'])){
$database->exportToExcel();
}
if(isset($_POST['pdf'])){
$database->exportToPdf();
}
上面的代码允许我们确定哪个按钮被按下,然后调用数据库类中的相应方法。
然后应用程序将导入CSV文件,将记录导出为用户指定的Excel或PDF。
与数据库的连接
Database 类扩展了mysqli 。在类的构造函数中,我们指定了server,username,password, 和type of database 。
这样做可以确保每当数据库类被实例化时,都会调用与数据库的连接。
class Database extends mysqli{
private $state = false;
private $server = "localhost";
private $databaseUser = "root";
private $userPassword = "";
private $databaseName = "bulk-op"
private $state = false;
public function __construct(){
parent::__construct($server, $databaseUser, $userPassword, $databaseName);
if($this->connect_error){
echo "Cannont connect to the database becauser : ".$this->connect_error;
}
}
}
批量导入功能
批量导入函数的工作原理是从Excel文件中读取数据,将其转换为数组,然后运行数组并将每个元素插入数据库。
执行批量导入的第一步是以阅读模式打开一个Excel文件。在读取单行时,我们使用implode() 函数用逗号(,)分隔数据条目。
然后我们调用SQL INSERT 查询,将数据添加到相应的数据库字段中。
如果查询失败,私有变量state 被设置为false ,并抛出一个错误,表明导入程序不成功。否则,将向用户发送一个成功警报。
public function importFile($fileToImport){
//open file in reading mode
$fileToImport = fopen(fileToImport, 'r');
// read the file row by row separating the column elements by comma
while($record = fgetcsv(fileToImport)){
$valuesExtracted = "'". implode("','", $record)."'";
//call the insert mysql query
$sql = "INSERT INTO employee(fname, lname, department, age) VALUES(".$valuesExtracted.")";
//confirm is the query is executed
if($this->query($sql)){
$state = true;
}else{
$state = false;
}
}
if($state = true){
echo "Succefully imported records!";
}else{
echo "There was in erro fetching the records. Check and try again";
}
}
检索数据库记录
在用户界面工作时,我们调用了方法$database->getRecords() 。
在这一步中,我们将编写当这个函数被调用时将执行的代码。
首先,我们使用MySql查询从雇员表中选择所有内容,并以降序方式排序。
然后,对于结果中的每一行,我们提取列元素,并将其分配给与表中的列名相对应的一个变量。
public function getRecords(){
$count = 0;
$query = "SELECT * FROM employee ORDER BY ID DESC";
$result = $this->query($query);
while ($record = $result->fetch_assoc()) {
$fname = $record['fname'];
$lname = $record['lname'];
$dpt = $record['department'];
$age = $record['age'];
$count +=1;
?>
<tr>
<th scope="row"><?php echo $count ?></th>
<td><?php echo $fname ?></td>
<td><?php echo $lname ?></td>
<td><?php echo $dpt ?></td>
<td><?php echo $age ?></td>
</tr>
<?php
}
}
批量导出到Excel
在导出到Excel的功能中,我们选择我们希望导出的值。
接下来,我们以阅读模式打开一个文件,然后将从雇员表中获取的数据逐行写入文件。
请注意,我们也为每个导出的文件创建一个独特的名称,以区别它们。
每个文件都将以records 为前缀,并在末尾加一个CSV 。
public function exportToExcel(){
$this->state = false;
//select the desired fielfs from db
$sql = "SELECT t.fname, t.lname, t.department, t.age FROM employee as t";
//query the database
$temp = $this->query($sql);
//check if the querry returned data and the rows fetched is greater than 0
if(!empty($temp) && $temp->num_rows > 0){
//create a new filename
$filename = "records".uniqid().".csv";
//open the file in the files directory of the project in writing mode
$file = fopen("files/".$filename, "w");
//loop the records fetched and write them to the file opened
while($row = $temp->fetch_array(MYSQLI_NUM)){
if(fputcsv($file, $row)){
//if success, set state to true
$this->state = true;
}else{
//set state to flase
$this->state = false;
}
}
//send success message if state is true
if($state = true){
echo "Succefully exported records!";
}else{
echo "There was in error fetching the records. Check and try again";
}
//close the file
fclose($file);
}else{
//the querry returned no data or the database is emplty
echo "NO data fecthed".$this->error;
}
}
批量导出为PDF
PDF是可移植文档格式的缩写。它是展示文件和尽量减少编辑的流行格式之一。
为了将我们的数据库记录导出到PDF,我们需要使用一个叫做fpdf的小库。
下载并提取该库,在你的项目中新建一个名为fpdf 的folder 。
在Database.php 文件的顶部,添加以下代码。
require('fpdf/fpdf.php');
为了使用这个库导出数据,我们首先选择记录,并将每一行的元素分配到应该出现的相应单元格。
我们还指定文件的名称和视图的格式。我们可以说明我们是否需要将文件下载或在浏览器中显示。
在我的案例中,我把我的文件称为records.pdf ,并在浏览器中显示。
public function exportToPdf(){
//getting recods form the database
$query = "SELECT * FROM employee ORDER BY ID DESC";
$result = $this->query($query);
$count = 0;
//creating a new instance of the fpdf class for our data
$pdf = new Fpdf();
$pdf-> AddPage();
$pdf->SetFont('Arial','',9);
$pdf->Cell(15,8,"S/NO",1);
$pdf->Cell(45,8,"First Name",1);
$pdf->Cell(40,8,"Last Name",1);
$pdf->Cell(40,8,"Department",1);
$pdf->Cell(40,8,"Age",1);
//writing every row fecthed to the pdf file
while ($record = $result->fetch_assoc()){
$count +=1;
$pdf->Ln();
$pdf->Cell(15,8,$count,1,0,'C');
$pdf->Cell(45,8,$record['fname'],1);
$pdf->Cell(40,8,$record['lname'],1);
$pdf->Cell(40,8,$record['department'],1);
$pdf->Cell(40,8,$record['age'],1,0,'C');
}
//specify the output file name and view formar
$pdf->output('records.pdf', 'I');
}
创建一个数据库并运行该应用程序
打开phpmyadmin ,然后创建一个名为bulk_up 的新数据库。这与我们在Database.php 文件中编写构造函数时指定的名称相同。
在bulk_up 数据库中,创建一个名为teammember 的表,其属性如下。
- id
- fname
- lname
- 部门
- 年龄
将项目文件夹迁移到XAMPP 安装目录下的htdocs 文件夹中。
接下来,启动MySQL和Apache服务器,然后浏览你的浏览器,查看该项目。


总结
本文指导读者如何在PHP中使用MySQL数据库进行批量操作。在处理大量数据时,批量操作很有帮助。
我们已经建立了一个项目,列出了员工的信息。它还允许人们将记录导入和导出到Excel和PDF。
我们还讨论了如何设置fpdf library ,并使用它将数据导出为PDF格式。