How to display a doc file in PHP from the database
In this article, you will learn how to display a DOC file on a webpage using the PHP programming language. We generally use a document to store more text formatting information that can be easily created, stored, and shared. During web development, it can also be possible to receive a request to display the document in the web browser.
In PHP, the developer can easily complete this task using an iframe. HTML iframe is an inline frame that is used to embed another document within the current HTML document. Here, we have explained the step-by-step process to fetch the document information from the database and display it on a web page.
Suppose we have a table 'infodoc' in the database as follows. You can use your existing database or copy and paste this into MySQL.
CREATE TABLE IF NOT EXISTS `infodoc` (
`fileid` int(11) NOT NULL AUTO_INCREMENT,
`filename` varchar(150) NOT NULL,
`directory` varchar(150) NOT NULL,
`created_date` date NOT NULL,
PRIMARY KEY (`fileid`)
)
INSERT INTO `infodoc` (`fileid`, `filename`, `directory`, `created_date`) VALUES
(1, 'etp.docx', '/document/', '2020-06-22');
Next, we have created a PHP file 'index.php' and written the database connection code at the top. For this, we have used the Object Oriented PHP MySQLi connection code. Then, it fetched the docx file name and directory using a select statement.
The only way to embed the Doc file on a web page is to use Google Reader. But it has the limitation of only opening public access files for display in the browser. We can't open password protected files.
<?php
// Database Connection
$conn = new mysqli('hostname', 'username', 'password', 'database');
//Check for connection error
$select = "SELECT * FROM `infodoc`";
$result = $conn->query($select);
while($row = $result->fetch_object()){
$doc = $row->filename;
$path = $row->directory;
$date = $row->created_date;
}
echo '<h1>Here is the Document information</h1>';
echo '<strong>Created Date : </strong>'.$date;
echo '<strong>File Name : </strong>'.$doc;
?>
<br/><br/>
<iframe src="https://docs.google.com/gview?url=&embedded=true" width="90%" height="500px">
</iframe>
When we open the 'index.php' in the browser, it returns something like this.
Related Articles
PHP remove last character from stringHow to lock a file using PHP
Complete HTML Form Validation in PHP
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
PHP create word document from html
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
PHP Connection and File Handling on FTP Server