Home >Backend Development >PHP Tutorial >PHP method to implement uploading images and saving them to the database_PHP tutorial
This article mainly introduces the method of uploading pictures to the database in php. Multiple systems can be implemented by saving pictures in the database. The function of server sharing files is of great practical value. Friends who need it can refer to it
PHP implements the method of uploading images and saving them to the database. Share it with everyone for your reference. The specific analysis is as follows:
PHP uploads images, generally using the move_uploaded_file method to save them on the server. But if a website has multiple servers, it needs to publish the images to all servers for normal use (except those using image servers)
If the image data is saved in the database, files can be shared among multiple servers to save space.
First of all, the image file is binary data, so the binary data needs to be saved in the mysql database.
The mysql database provides the BLOB type for storing large amounts of data. BLOB is a binary object that can accommodate data of different sizes.
There are four types of BLOB, which are the same except for the maximum amount of information stored. Different types can be used depending on your needs.
TinyBlob Max 255B
Blob maximum 65K
MediumBlob Max 16M
LongBlob Max 4G
Data table photo, used to save image data, the structure is as follows:
The code is as follows:
upload_image_todb.php:
The code is as follows:
// Determine action
$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';
//Upload pictures
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 image list and upload form
?>
< /p>';
}
?>
}
?>
I hope this article will be helpful to everyone’s PHP programming design.