I am new to the php programming.I want to know how to store and retrieve images from the database.can u please help me how to store image in database and retrieve from the database.
Asked
Active
Viewed 3,134 times
2 Answers
1
Q. How to store images in database?
A. Do not store images in database. They explode.
Do not store binary data in a [relational] database. Store it in a filesystem - a database intended to store files.

HamZa
- 14,671
- 11
- 54
- 75

Your Common Sense
- 156,878
- 40
- 214
- 345
1
There are different ways to store images in a database and above is one method that you can use:
CREATE TABLE `employees` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`empname` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`profile_pic` LONGBLOB NULL,
`ext` VARCHAR(5) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
PRIMARY KEY (`id`)
)
And the php code:
<?php
$dbh = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
mysql_select_db("test");
$data = file_get_contents($image_file_name);
$data = mysql_real_escape_string($data);
mysql_query("INSERT INTO imagestableblob(data) VALUES ('$data')");
?>
Here's a tutorial to store images in a DB or you can also refer to this.
But it's recommended to store images in file based system. For this you need to create id,name,path etc columns and map it wherever you need to access by image id.

HamZa
- 14,671
- 11
- 54
- 75

Anil Gupta
- 632
- 4
- 16
-
3**1)** Don't use mysql_, use mysqli/pdo **2)** Don't store images in a DB, store it on your harddrive and save the path to it in your DB. – HamZa Jun 18 '13 at 13:07
-
-
Have you tried,It get image data and then we can store it in db. It depends on requirement where you want to store images either file based system or in database. File based system is recommended. – Anil Gupta Jun 19 '13 at 08:46
-
Hi @HamZa have you store images in database, If no then try and please reply whether we need supply images path ? – Anil Gupta Jun 19 '13 at 08:49
-
@AnilGupta Just because you *can* do something doesn’t mean that you *should*. IMO it's bad to store images in a DB. So your solution may be correct, but not recommended. – HamZa Jun 19 '13 at 09:01
-
yes recommended is file-based-system but question was more specific to store image in db, I think, If how someone can vote for down – Anil Gupta Jun 19 '13 at 09:06
-
1
-
@AnilGupta For your information, I didn't downvote. I think every answer with efforts or intending to help doesn't deserve it. Take care :) – HamZa Jun 19 '13 at 09:27
-
1Thanks @HamZa, I will take care point given by you and i will always try to use recommend answer also – Anil Gupta Jun 19 '13 at 09:43