How do I insert images into the database, and fetch it from the database and display using PHP?
I have tried many times as i am a beginner of php please help me out.
You can use a BLOB field for storing binary data, but please be aware that the performance may be moderate. It's almost always better to store the image as a file on disk and just store the file name in the database. To fetch the image from db, you will need to read the whole image into memory, which is a waste of resources. It's better to offload the image handling to the web server which can stream the image to the client.
As much as this is not a recommended practice, if you have your heart set on doing this, there are a pile of tutorials online which will walk you through how to do this:
You can create a table like so:
CREATE TABLE `image` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`filename` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`mime_string` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`data` longblob NOT NULL,
`data_size` int(11) NOT NULL,
`hash` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`compressed` tinyint(4) NOT NULL,
`remote_id` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `image_I_1` (`hash`),
KEY `image_I_2` (`remote_id`)
) ENGINE=InnoDB AUTO_INCREMENT=125 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT
When you write the file back to the output, you'll have to write the HTTP header content type to the same as the mime type:
header( 'Content-type', 'image/png' );
Which is why you store the mime type along with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.