How can i record an image file to database and read it from database with MYSQL and PHP ? Thanks
Asked
Active
Viewed 375 times
1 Answers
0
Here goes a very basic example:
MySQL
CREATE TABLE 'picture' (
'id' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'image' LONGBLOB NOT NULL,
PRIMARY KEY ('id')
)
PHP
$image = file_get_contents('myimage.jpg');
// your db connection code here..
mysql_query("INSERT INTO picture (image) VALUES ('$image');
Bare in mind storing images in the database is not a very good plan. It is better to keep the images in a directory and just save the path in the database.

AndreFeijo
- 10,044
- 7
- 34
- 64
-
Correct. Then to display the image, create a PHP file and have it grab the `image` column from `picture` then just echo it out. But don't forget to change the content type, `header("Content-type: image/jpg");` but you'll need to determine which type of image it is in order to set the right one – Mark Eriksson Mar 09 '16 at 07:58
-
Can u tell me why keep the images in a directory and save the path in the database is better than storing images in the database ? Thanks – Quang Đức Mar 09 '16 at 08:03
-
Database storage is usually more expensive than file system storage; You can super-accelerate file system access with standard off the shelf products for example, many web servers use the operating system's sendfile() system call to asynchronously send a file directly from the file system to the network interface. Images stored in a database don't benefit from this optimization; It is more complex to manage integrity between db metadata and file system data. – AndreFeijo Mar 09 '16 at 08:13