Home >Database >Mysql Tutorial >How Can I Effectively Store and Retrieve Binary Data in MySQL?
Working with Binary Data in MySQL
Storing binary data in MySQL is a common requirement in various applications. The specific data type to use for this purpose is BLOB (Binary Large Object).
BLOB Data Type
BLOB is a special column type designed to handle binary data. It can store large volumes of binary data, including images, videos, documents, or any other type of non-textual content.
Creating a BLOB Column
To create a BLOB column in a MySQL table, use the following syntax:
CREATE TABLE table_name ( column_name BLOB NOT NULL );
The NOT NULL constraint ensures that the column cannot contain empty values.
Inserting Binary Data into BLOB
You can insert binary data into a BLOB column using the following methods:
Example
The following PHP code demonstrates how to insert a binary image into a BLOB column:
$con = mysqli_connect('host', 'username', 'password', 'dbname'); $stmt = mysqli_prepare($con, "INSERT INTO table_name (column_name) VALUES (?)"); $image = file_get_contents('image.png'); mysqli_stmt_bind_param($stmt, "b", $image); mysqli_stmt_execute($stmt);
Retrieving Binary Data from BLOB
To retrieve binary data from a BLOB column, use the same methods as for inserting. Be sure to handle the data as binary, as it is not stored as text in MySQL.
The above is the detailed content of How Can I Effectively Store and Retrieve Binary Data in MySQL?. For more information, please follow other related articles on the PHP Chinese website!