Summary: in this tutorial, you will learn how to store binary data in the PostgreSQL database using PHP.
BLOB stands for the binary large object used to store binary data such as the content of a file.
PostgreSQL does not support the BLOB data type. However, you can use the BYTEA data type for storing the binary string.
We’ll create a new table called company_files to store the binary string:
We will store the content of a file in the file_data column. In addition, we will read the files from the assets/images folder and insert them into the company_files table.
To work with the binary data, we create a new class named BlobDB.
Inserting binary data
The following insert() method reads data from a file specified by the $pathToFile parameter and inserts it into the company_files table.
How it works.
First, call the pgsqlLOBCreate() method of the PDO object to create a new large object and get the OID of the large object.
Next, call the pgsqlLOBopen() method to open a stream on the large object to write data to it.
Then, read data from a file and copy the data from the file stream to the large binary object.
After that, prepare the INSERT statement and execute it.
Finally, call the lastInsertId to get the generated ID.
Note that the pgsqlLOBCreate() method must be called within a transaction, therefore, we place all the logic within a transaction.
Place the following code in the index.php file to insert the content of the google.png file into the company_files table.
Launch the index.php file, we get the following message.
To verify the insert operation, we use the following query:
Querying binary data
The following read() method reads the BLOB data from the company_files table and outputs the file content to the web browser:
Next, execute the SELECT statement by calling the execute() method.
Then, pass the OID to the pgsqlLOBOpen() method of a PDO object to get the stream.
After that, output the stream based on the mime type of the file.
Finally, because the pgsqlLOBopen() must be called within a transaction, we called the beginTransaction() at the beginning of the method.
To test the read() method, we place the following code in the file.php:
The file.php file gets the id value from the query string and outputs the file stored in the company_files table to the web browser.
Deleting binary data
The following delete() method deletes a row in the company_files table.
How it works.
First, get the OID object from the file_data column.
Second, use the pgsqlLOBUnLink() method to remove the BLOB data and execute the DELETE statement to remove a row specified by an ID in the company_files table.
In this tutorial, you have learned how to insert, query, and delete binary data in the PostgreSQL database.