Introduction to MySQL BLOB
Blob is the data type in MySQL that helps us store the object in the binary format. It is most typically used to store the files, images, etc media files for security reasons or some other purpose in MySQL. It can store and hold a variable amount of the data and four types of blob can be used in MySQL namely – LONGBLOB, MEDIUMBLOB, BLOB, and TINYBLOB. All these types differ in the storage space required and the maximum length that can e stored. These datatype values are mostly treated as byte strings or binary strings.
The BLOB values contain the binary character set and collation. The bytes that are stored in such column values have numeric values based on which the sorting and comparison are done whenever performed in MySQL. In this article, we will learn about the BLOB datatype and how we can declare the columns of the table as BLOB, further we will discuss the behavior of the BLOB values for different settings of strict mode and see the examples related to BLOB values.
BLOB Datatype
The maximum row size of the table in MySQL is 65535 that represents the internal capability of the row even though the storage engine has larger capability support for rows. This maximum size of the row does not include the BLOB or TEXT data typed column in it. Along with the is for row buffer the BLOB valued data is stored in different areas of the memory and the allocation of the memory to this type of value differs for different storage engines. Each storage engine uses a different method to handle the data of such datatype.
The storage requirement for all the blob datatypes is as given below –
- TINYBLOB – length+ 1 bytes, where length< 2^8
- BLOB – length+ 2 bytes, where length< 2^16
- MEDIUMBLOB – length+ 3 bytes, where length< 2^24
- LONGBLOB – length+ 4 bytes, where length< 2^32
where the length stands for the original length of the character string that the blob data typed column contains.
There are certain things that you should know about the BLOB datatype and are listed below –
- The BLOB data type is a variable-length column and hence it is regarded as the VARBINARY column. However, it differs from the VARBINARY in certain ways. Whenever the BLOB column is used for indexing, it is necessary to mention the length of the prefix that will be used for indexing and the default value cannot be assigned to the BLOB column.
- Whenever the strict mode in MySQL is disabled and we try to insert the value in BLOB column that exceeds the maximum length of the column then the value that can fit the column is truncated from the original value being inserted and only the truncated value is inserted along with the generation of warning.
- If the strict mode is enabled in Mysql the truncation of the value exceeding the maximum length of the column is prevented and an error is raised saying that the value being inserted exceeds the defined column length.
- Whenever we perform sorting on the BLOB column then only the first max_sort_length bytes are considered for sorting. max_sort_length variable has the default value of 1024. However, we can further change the value of max_sort_length and increase it to consider that many bytes of the value while sorting and grouping the data based on the BLOB column.
- The type of the BLOB determines the maximum size that the column can have however the actual largest possible size of the value that can be transmitted between client and server depends on the size of the buffers used in communication and the available memory. The maximum capacity of the size of the buffer can be changed by simply changing the value of the max_allowed_packet variable. The value of this variable needs to be changed at the server as well as client size for it to work correctly.
Examples of MySQL BLOB
We will create a table named gallery that will contain the id, name, and image columns. The image column will be of BLOB datatype. We can use the following query to create our table –
Code:
CREATE TABLE gallery (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (255) NOT NULL,
image BLOB NOT NULL
);
Output:
In PHP, we can use PDO to insert the values in tables with blob datatype columns. We will see a program in PHP which will show how we can insert and retrieve the blob values to and from database which is as follows –
Code:
<?php
class galleryBlob {
const DB_HOST = 'localhost';
const DB_NAME = 'educba';
const DB_USER = 'username';
const DB_PASSWORD = 'password';
public function __construct() {
$conStr = sprintf("mysql:host=%s;dbname=%s;charset=utf8", self::DB_HOST, self::DB_NAME);
try {
$this->pdo = new PDO($conStr, self::DB_USER, self::DB_PASSWORD);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function insertImage($filePath, $name) {
$blob = fopen($filePath, 'rb');
$sql = "INSERT INTO gallery(name,image) VALUES(:name,:image)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':image', $blob, PDO::PARAM_LOB);
return $stmt->execute();
}
public function selectImage($id) {
$sql = "SELECT name,
image
FROM gallery
WHERE id = :id;";
$stmt = $this->pdo->prepare($sql);
$stmt->execute(array(":id" => $id));
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $image, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
return array("name" => $name,
"image" => $image);
}
public function __destruct() {
$this->pdo = null;
}
}
$sampleImage = new galleryBlob();
$sampleImage->insertImage('sample.jpg',"image/jpg");
$a = $sampleImage->selectImage(1);
header("Content-Type:" . $a['name']);
echo $a['image'];
?>
The output of the above code when the file is saved with name educba.php and run on the browser is as follows because this image was inserted by me and had name sample.jpg-
which shows the image that we stored in the SQL table gallery. Let us retrieve the record in MySQL and check the contents of the gallery table –
select id, name from gallery;
Output:
When we try to retrieve the blob value by using the following query statement the output is too large due to the jpg file stored in the image column of blob type which makes resultset vast and unreadable on the terminal because jpg file is not parsable on the terminal.
select * from gallery;
Output:
Conclusion
The blob type is used in MySQL to store media files like images, pdf files, videos, reports, etc. The precautions to be taken while using this type as discussed above.
Recommended Articles
This is a guide to MySQL BLOB. Here we discuss the introduction, BLOB Datatype, and examples along with code implementation respectively. You may also have a look at the following articles to learn more –
12 Online Courses | 10 Hands-on Projects | 92+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses