《PHP學(xué)習(xí):php實(shí)現(xiàn)上傳圖片保存到數(shù)據(jù)庫的方法》要點(diǎn):
本文介紹了PHP學(xué)習(xí):php實(shí)現(xiàn)上傳圖片保存到數(shù)據(jù)庫的方法,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)例php實(shí)現(xiàn)上傳圖片保存到數(shù)據(jù)庫的辦法.分享給大家供大家參考.具體分析如下:
PHP實(shí)例php 上傳圖片,一般都使用move_uploaded_file辦法保存在服務(wù)器上.但如果一個網(wǎng)站有多臺服務(wù)器,就需要把圖片發(fā)布到所有的服務(wù)器上才能正常使用(使用圖片服務(wù)器的除外)
如果把圖片數(shù)據(jù)保存到數(shù)據(jù)庫中,多臺服務(wù)器間可以實(shí)現(xiàn)文件共享,節(jié)省空間.
PHP實(shí)例首先圖片文件是二進(jìn)制數(shù)據(jù),所以需要把二進(jìn)制數(shù)據(jù)保存在mysql數(shù)據(jù)庫.
mysql數(shù)據(jù)庫提供了BLOB類型用于存儲大量數(shù)據(jù),BLOB是一個二進(jìn)制對象,能容納不同大小的數(shù)據(jù).
PHP實(shí)例BLOB類型有以下四種,除存儲的最大信息量不同外,其他都是一樣的.可根據(jù)需要使用不同的類型.
PHP實(shí)例TinyBlob?????? 最大 255B
Blob????????????? 最大 65K
MediumBlob? 最大 16M
LongBlob????? 最大 4G
PHP實(shí)例數(shù)據(jù)表photo,用于保存圖片數(shù)據(jù),結(jié)構(gòu)如下:
PHP實(shí)例upload_image_todb.php:
PHP實(shí)例// 判斷action?
$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';?
PHP實(shí)例// 上傳圖片?
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:upload_image_todb.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="upload_image_todb.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="upload_image_todb.php?action=show&id='.$val['id'].'&t='.time().'" width="150"></p>';?
??? }?
?>?
</body>?
</html>?
<?php?
}?
?>
PHP實(shí)例
PHP實(shí)例
PHP實(shí)例希望本文所述對大家的php程序設(shè)計有所贊助.
維易PHP培訓(xùn)學(xué)院每天發(fā)布《PHP學(xué)習(xí):php實(shí)現(xiàn)上傳圖片保存到數(shù)據(jù)庫的方法》等實(shí)戰(zhàn)技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養(yǎng)人才。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/12266.html