Home >php教程 >php手册 >PHP把图片存入数据库(非路径)

PHP把图片存入数据库(非路径)

WBOY
WBOYOriginal
2016-06-06 19:33:21814browse

大部分人的图片上传都是保存一个路径到数据库,这样在插入时确实快,也符合web的特点,但是在删除时就很麻烦,需要找到文件并删除,该代码能够把代码直接存入数据库,删除时一并删除。 请注意:这样的话数据库大小会激增,请酌情使用 无 CREATE TABLE `upload

大部分人的图片上传都是保存一个路径到数据库,这样在插入时确实快,也符合web的特点,但是在删除时就很麻烦,需要找到文件并删除,该代码能够把代码直接存入数据库,删除时一并删除。
请注意:这样的话数据库大小会激增,请酌情使用
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;
<!doctype html>
    <html>
<head>
    <title>
        Post-Image
    </title>
</head>
<body>
<form action="post.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file"/>
    <input type="submit" value="OK"/>
</form>
</body>
    </html>
<?php
if ($_FILES["file"]["error"] > 0)
{
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
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 '<pre class="brush:php;toolbar:false">';
    try{
        $pdo = new PDO($dsn,'root','root');
        $pdo->exec("INSERT INTO `upload`(`type`,`data`) values ('$type',0x$data)");
        $id = $pdo->lastInsertId();
        echo 'upload success!<a href="view.php?id='.$id.'">View</a>';
        $pdo = null;
    }catch (PDOException $e){
        echo $e->getMessage();
    }
    echo '
'; fclose($fp); }
<?php
$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();
}
Statement:
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
Previous article:最简单的PHP目录文件遍历Next article:水仙花开