PHP-mysql存儲照片的兩種方式php
方式一:把圖片數據存儲在數據庫中(二進制)html
數據庫代碼:mysql
CREATE TABLE `photo` (
`id` int(10) unsigned NOT NULL auto_increment,
`type` varchar(100) NOT NULL,
`binarydata` mediumblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;sql
展示代碼:數據庫
<?php // 鏈接數據庫 $conn=@mysql_connect("localhost","root","root") or die(mysql_error()); @mysql_select_db('test',$conn) or die(mysql_error()); // 判斷action $action = isset($_REQUEST['action'])? $_REQUEST['action'] : ''; // 上傳圖片 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:test.php'); exit(); // 顯示圖片 }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{ // 顯示圖片列表及上傳表單 ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title> upload image to db demo </title> </head> <body> <form name="form1" method="post" action="test.php" enctype="multipart/form-data"> <p>圖片:<input type="file" name="photo"></p> <p><input type="hidden" name="action" value="add"><input type="submit" name="b1" value="提交"></p> </form> <?php $sqlstr = "select * from photo order by id desc"; $query = mysql_query($sqlstr) or die(mysql_error()); $result = array(); while($thread=mysql_fetch_assoc($query)){ $result[] = $thread; } foreach($result as $val){ echo '<p><img src="test.php?action=show&id='.$val['id'].'&t='.time().'" width="150"></p>'; } ?> </body> </html> <?php } ?>
結果截圖:服務器
方式二:經過在數據庫中存儲圖片的路徑來實現圖片的存儲post
(1)將圖片上傳到服務器fetch
(2)取出圖片的路徑存放到數據庫中ui
(3)使用時取出數據庫的路徑orm
具體實現有興趣的能夠去完成,沒有什麼技術難點,歡迎你們交流!
方法優劣:
多服務器的時候應該使用第一種方法較好,單服務器第二種效率高一點