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
Release: 2024-12-27 18:21:11
Original
642 people have browsed it

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 ''
);
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template