Home > Backend Development > PHP Tutorial > PHP upload image and save it to database example sharing_PHP tutorial

PHP upload image and save it to database example sharing_PHP tutorial

WBOY
Release: 2016-07-13 10:36:12
Original
844 people have browsed it

Most people upload pictures by saving a path to the database, which is really fast when inserting and conforms to the characteristics of the web. However, it is very troublesome when deleting. You need to find the file and delete it. This code can directly Save it to the database and delete it when you delete it. Please note: If this happens, the database size will increase. Please use it as appropriate

Table structure

Copy code The code is as follows:

CREATE TABLE `upload` (
`id` int (10) unsigned NOT NULL AUTO_INCREMENT,
`type` varchar(20) NOT NULL,
`data` mediumblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= 1 DEFAULT CHARSET=utf8;

index.html

Copy code The code is as follows:



<br>   Post-Image<br> 








post.php

Copy code The code is as follows:

if ($_FILES[ "file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "
";
}
else
{
$type = $_FILES["file"]["type"];
$size = $_FILES['file']['size'];
$tmp=$_FILES["file"]["tmp_name"];
$fp = fopen($tmp,'rb');
$data = bin2hex(fread($fp,$size)) ;
$dsn='mysql:host=localhost;dbname=test';
echo '
';<br> try{<br> $pdo = new PDO($dsn,'root' ,'root');<br> $pdo->exec("INSERT INTO `upload`(`type`,`data`) values ​​('$type',0x$data)");<br> $id = $pdo->lastInsertId (); pdo = null;<br> }catch (PDOException $e){<br> echo $e->getMessage();<br> }<br> echo '
';
fclose($ fp);
}


view.php


Copy code The code is as follows:
$id = $_GET ['id'];
if(is_numeric($id)){
$dsn='mysql:host=localhost;dbname=test';
try{
$pdo = new PDO( $dsn,'root','root');
$rs = $pdo->query('select * from `upload` where `id`='.$id);
$row = $ rs->fetchAll();
        $data = $row[0];
       header("Content-Type:${data['type']}"); data'];
$pdo = null;
}catch (PDOException $e){
echo $e->getMessage();
}
}else{
exit ();
}



http://www.bkjia.com/PHPjc/740205.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/740205.htmlTechArticleMost people upload pictures by saving a path to the database, which is really fast when inserting and is also consistent with the web features, but it is very troublesome when deleting. You need to find the file and delete it...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template