以下是一个基本的示例代码,可以用来从数据库获取 PDF 文件并在屏幕上展示。
// 连接数据库
$connection = mysqli_connect("localhost", "username", "password", "dbname");
// 获取 PDF 文件流
$query = "SELECT pdf_content FROM pdf_table WHERE pdf_id = '1'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0) {
$pdfData = mysqli_fetch_assoc($result)['pdf_content'];
// 设置 header 以显示 PDF
header("Content-type: application/pdf");
header("Content-Length: " . strlen($pdfData));
// 输出 PDF 数据
echo $pdfData;
} else {
echo "PDF 文件不存在";
}
// 关闭数据库连接
mysqli_close($connection);
该代码中,我们首先使用 mysqli 函数连接到数据库,并执行查询以获取 PDF 数据。随后,我们通过 header 设置来指定响应类型和内容长度,并将 PDF 数据直接输出到浏览器中,从而实现在屏幕上显示 PDF 的功能。最后,我们将数据库连接关闭以免引起资源浪费和潜在的安全风险。