图片存入数据库的解决方案,图片的保存方法有很多种,通学是将图片保存到文件夹,再将路径存入数据库中,这样也便于使用与管理,但有时候也会用到将图片要保存到数据库中,下面我将图片保存到数据库中,php解决方案分享给大家。
创建数据库:
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>'; 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 '</pre>'; 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(); }
快来试试吧!