Home >Backend Development >PHP Tutorial >How to Store and Retrieve Images in a MySQL Database Using PHP?

How to Store and Retrieve Images in a MySQL Database Using PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 06:31:13293browse

How to Store and Retrieve Images in a MySQL Database Using PHP?

Storing and Retrieving Images in MySQL Database Using PHP

Storing and retrieving images in a MySQL database is a common task when developing web applications that handle images. This article demonstrates how to achieve this using PHP.

Creating a Database Table

First, create a table in your MySQL database to store the images. You can use the following SQL statement to create a table named testblob:

CREATE TABLE testblob (
    image_id TINYINT(3) NOT NULL DEFAULT '0',
    image_type VARCHAR(25) NOT NULL DEFAULT '',
    image BLOB NOT NULL,
    image_size VARCHAR(25) NOT NULL DEFAULT '',
    image_ctgy VARCHAR(25) NOT NULL DEFAULT '',
    image_name VARCHAR(50) NOT NULL DEFAULT ''
);

Inserting an Image into the Database

To insert an image into the database, read the image data from a file and save it as a variable. You can then use the following PHP code:

$imgData = file_get_contents($filename);
$size = getimagesize($filename);
// Connect to MySQL database
... (connection code) ...

$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
);

mysql_query($sql);

Retrieving an Image from the Database

To retrieve an image from the database and display it on a web page, use the following PHP code:

// Connect to MySQL database
... (connection code) ...

$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

The above is the detailed content of How to Store and Retrieve Images in a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn