How can I insert an image in MySQL and then retrieve it using PHP?
I have limited experience in either area, and I could use a little code to get me started in figuring this out.
How can I insert an image in MySQL and then retrieve it using PHP?
I have limited experience in either area, and I could use a little code to get me started in figuring this out.
Beware that serving images from DB is usually much, much much slower than serving them from disk.
You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.
OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead.
That's a difference between being able to serve 20 or 2000 images in parallel on one machine.
So don't do it unless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.
Personally i wouldnt store the image in the database, Instead put it in a folder not accessable from outside, and use the database for keeping track of its location. keeps database size down and you can just include it by using PHP. There would be no way without PHP to access that image then
My opinion is, Instead of storing images directly to the database, It is recommended to store the image location in the database. As we compare both options, Storing images in the database is safe for security purpose. Disadvantage are
If database is corrupted, no way to retrieve.
Retrieving image files from db is slow when compare to other option.
On the other hand, storing image file location in db will have following advantages.
It is easy to retrieve.
If more than one images are stored, we can easily retrieve image information.
Instead of storing images in database store them in a folder in your disk and store their location in your data base.
First you create a MySQL table to store images, like for example:
Then you can write an image to the database like:
You can display an image from the database in a web page with:
i also recommend thinking this thru and then choosing to store images in your file system rather than the DB .. see here: Storing Images in DB - Yea or Nay?