This article mainly introduces the example of storing php uploaded images into the database. if you need a friend, you can refer to the pictures uploaded by most people. they save a path to the database, which is indeed fast during insertion, it is also in line with the characteristics of the web, but it is very troublesome to delete, you need to find and delete the file, the code can directly store the code in the database, delete it at the same time. Please note: In this case, the database size will surge, please use it as appropriate
Table structure
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
The code is as follows:
<BR> Post-Image <BR>
Post. php
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'
';
try{
$pdo = new PDO($dsn,'root','root');
$pdo->exec("INSERT INTO `upload`(`type`,`data`) values ('$type',0x$data)");
$id = $pdo->lastInsertId();
echo 'upload success!View';
$pdo = null;
}catch (PDOException $e){
echo $e->getMessage();
}
echo '
';
Fclose ($ fp );
}
View. php
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']}");
Echo $ data ['data'];
$ Pdo = null;
} Catch (PDOException $ e ){
Echo $ e-> getMessage ();
}
} Else {
Exit ();
}