Example of uploading an image to a database using php,
Example of uploading an image to a database using php
Php uploads images. Generally, the move_uploaded_file method is used to store images on the server. However, if a website has multiple servers, you need to publish images to all servers for normal use (except for image servers)
If you save image data to a database, multiple servers can share files to save space.
First, the image file is binary data, so you need to save the binary data in the mysql database.
Mysql database provides the BLOB type for storing a large amount of data. BLOB is a binary object that can accommodate data of different sizes.
There are four types of BLOB, except the maximum amount of information stored is different, the others are the same. You can use different types as needed.
TinyBlob Max. 255B
Blob Max 65 K
MediumBlob up to 16 MB
Up to 4 GB LongBlob
The data table photo is used to save image data. Its structure is as follows:
CREATE TABLE `photo` ( `id` int(10) unsigned NOT NULL auto_increment, `type` varchar(100) NOT NULL, `binarydata` mediumblob NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Upload_image_todb.php
<? Php // connect to the database $ conn = @ mysql_connect ("localhost", "root", "") or die (mysql_error (); @ mysql_select_db ('Demo', $ conn) or die (mysql_error (); // judge action $ action = isset ($ _ REQUEST ['action'])? $ _ REQUEST ['action']: ''; // upload an image if ($ action = 'add ') {$ image = mysql_escape_string (file_get_contents ($ _ FILES ['photo'] ['tmp _ name']); $ type = $ _ FILES ['photo '] ['type']; $ sqlstr = "insert into photo (type, binarydata) values ('". $ type. "','". $ image. "')"; @ mysql_query ($ sqlstr) or die (mysql_error (); header ('location: upload_image_todb.php'); exit (); // display image} elseif ($ action = 'show') {$ id = isset ($ _ GET ['id'])? Intval ($ _ GET ['id']): 0; $ sqlstr = "select * from photo where id = $ id"; $ query = mysql_query ($ sqlstr) or die (mysql_error (); $ thread = mysql_fetch_assoc ($ query); if ($ thread) {header ('content-type :'. $ thread ['type']); echo $ thread ['binarydata']; exit () ;}} else {// display the image list and upload form?> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">