Home >Database >Mysql Tutorial >How to Insert and Retrieve Images from a MySQL Database Using PHP?

How to Insert and Retrieve Images from a MySQL Database Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 18:21:11651browse

How to Insert and Retrieve Images from a MySQL Database Using PHP?

Storing and Retrieving Images in MySQL Using PHP

Question:
How can I insert and retrieve images from a MySQL database using PHP?

Answer:

To store and retrieve images in MySQL using PHP, follow these steps:

Creating the MySQL Table:
Create a table in your database to store images. For 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 ''
);

Inserting Images:
To insert an image into 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);

Retrieving Images:
To display an image from the database in a web page:

$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 to Insert and Retrieve Images from 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