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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-10 21:55:10697browse

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

Storing and Retrieving Images in MySQL Database Using PHP

How can you preserve and access images within a MySQL database using PHP? For beginners, understanding this can be daunting. Here's a comprehensive guide to get you started:

Step 1: MySQL Database Preparation

Create a MySQL table for storing images, similar to this example:

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 ''
);

Step 2: Storing Image in Database

To write an image to the database:

$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
$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);

Step 3: Retrieving Image from Database

To display an image from the database:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$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 Can I 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