Set up the database
The difference between the text or integer type fields we usually use in the database and the fields that need to be used to save images lies in the amount of data that needs to be saved. MySQL database uses special fields to save large amounts of data, and the data type is BLOB.
MySQL database defines BLOB as follows: The BLOB data type is a large binary object that can store a variable amount of data. There are four types of BLOB, namely TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB. The difference lies in the maximum data length that each can save.
After introducing the data types we need to use, we can use the following statements to create a data table to save images.
CREATE TABLE Images (PicNum int NOT NULL AUTO_INCREMENT PRIMARY KEY, Image BLOB);
Write upload script
Regarding how to upload files, we will not introduce it here. Interested readers can refer to Related articles in "Web Tao Bar". Now, we mainly look at how to receive uploaded files and store them in the MySQL database. The specific script code is as follows, in which we assume that the name of the file upload domain is Picture.
If($Picture != "none") {
$PSize = filesize($Picture);
$mysqlPicture = addslashes(fread(fopen($Picture, "r" ), $PSize));
mysql_connect($host,$username,$password) or die("Unable to connect to SQL server");
@mysql_select_db($db) or die("Unable to select database");
mysql_query("INSERT INTO Images (Image) VALUES ($mysqlPicture)") or die("Cant Perform Query");
}else {
echo"You did not upload any picture ";
}
?>
In this way, we can successfully save the image to the database. If you have problems inserting images into MySQL, you can check the maximum packet size allowed by the MySQL database. If the setting value is too small, we will find the corresponding record in the error log of the database.
Next, we briefly explain the above script program. First, we check whether a file has been uploaded by "If($Picture != "none")". Then, use the addslashes() function to avoid data format errors. Finally, connect to MySQL, select the database and insert the picture.
Display pictures
After knowing how to import pictures into the database, we need to consider how to retrieve pictures from the database and display them in HTML pages. This process is a little more complicated. Let’s introduce the implementation process below.
Because PHP needs to send corresponding headers to display images, we will face the problem that only one image can be displayed at a time, because we cannot send other headers after sending the header.
In order to effectively solve this problem, we have written two files. Among them, the first file serves as the template of the HTML page and locates the display position of the image. The second file is used to actually output the file stream from the database as the SRC attribute of the tag.
The simple form of the first file can be as follows: