I'm trying to store an image in a MySQL database with the use of PHP. What is the datatype that I should use?
Asked
Active
Viewed 58 times
1
-
Datatype should be blob, but I would recommend storing images in a file system and only it's path in the DB table. Another great option is to use Amazon s3 buckets. – nice_dev Aug 24 '22 at 18:28
-
Some folks store the image itself in a directory and then store the filepath in the database, which I think is the best approach. If the pictures are small (like icons or what-have-you) you could convert the file's binary to Base64 and store that string in the database, as another option. You could also toss the binary into a `blob` type. Lots of viable options, you just have to figure out what works best for your requirements. – JNevill Aug 24 '22 at 18:29
1 Answers
-1
You can store the base64 string of the image in your table.
$img_file = "/tmp/my_image.jpg";
// get base64 string
$imgData = base64_encode(file_get_contents($img_file));
// insert into DB
$dbh->prepare("INSERT INTO my_image_table (img_base64) VALUES(?)");
$dbh->execute(array($imgData));
Make sure your data type of the column is big enough for the images. LONGTEXT can save up to 4GB.
Alternative: use BLOB or file-paths like others suggested.

Jura Herber
- 131
- 8