php實現上傳圖片儲存到資料庫的方法_PHP教程

來源:互聯網
上載者:User

php實現上傳圖片儲存到資料庫的方法


這篇文章主要介紹了php實現上傳圖片儲存到資料庫的方法,可通過將圖片儲存在資料庫實現多台伺服器共用檔案的功能,非常具有實用價值,需要的朋友可以參考下

php實現上傳圖片儲存到資料庫的方法。分享給大家供大家參考。具體分析如下:

php 上傳圖片,一般都使用move_uploaded_file方法儲存在伺服器上。但如果一個網站有多台伺服器,就需要把圖片發布到所有的伺服器上才能正常使用(使用圖片伺服器的除外)
如果把圖片資料儲存到資料庫中,多台伺服器間可以實現檔案分享權限設定,節省空間的。

首先圖片檔案是位元據,所以需要把位元據儲存在mysql資料庫。
mysql資料庫提供了BLOB類型用於儲存大量資料,BLOB是一個二進位對象,能容納不同大小的資料。

BLOB類型有以下四種,除儲存的最大資訊量不同外,其他都是一樣的。可根據需要使用不同的類型。

TinyBlob 最大 255B
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G

資料表photo,用於儲存圖片資料,結構如下:

代碼如下:

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 ;

upload_image_todb.php:

代碼如下:

// 串連資料庫
$conn=@mysql_connect("localhost","root","") or die(mysql_error());
@mysql_select_db('demo',$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: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{
// 顯示圖片列表及上傳表單
?>




upload image to db demo





$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 '

';
}
?>


}
?>

希望本文所述對大家的php程式設計有所協助。

http://www.bkjia.com/PHPjc/956982.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/956982.htmlTechArticlephp實現上傳圖片儲存到資料庫的方法 這篇文章主要介紹了php實現上傳圖片儲存到資料庫的方法,可通過將圖片儲存在資料庫實現多台伺服器...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.