上一篇:PHP腳本與數(shù)據(jù)庫(kù)功能詳解(上)
利用PHP將文件保存到數(shù)據(jù)庫(kù)
數(shù)據(jù)庫(kù)是數(shù)據(jù)組織、存儲(chǔ)的中心。將要處理的也可能是各種數(shù)據(jù),包括程序、文件、報(bào)表,甚至音頻、視頻數(shù)據(jù)。由于通過(guò)瀏覽器,個(gè)人用戶只能填寫少部分的個(gè)人簡(jiǎn)歷。因此,我們這里示范用戶個(gè)人簡(jiǎn)歷上載的功能。其他類型的數(shù)據(jù)可以模仿此例進(jìn)行操作。
首先是信息收集頁(yè)面。讓用戶選擇要上載的文件。此頁(yè)面的html代碼如下:
〈!-- begin of post.htm--〉
〈p〉 〈/p〉
〈form method="POST" action="insert.php" ENCTYPE="multipart/form-data"〉
〈p〉〈b〉個(gè)人簡(jiǎn)歷提交〈/b〉〈/p〉
〈p〉姓名:〈br〉
〈input type="text" name="Name" size="20"〉〈/p〉
〈p〉個(gè)人簡(jiǎn)介:〈br〉
〈textarea rows="2" name="Intro" cols="20"〉〈/textarea〉〈/p〉
〈p〉簡(jiǎn)歷文件:〈br〉
〈input type="file" name="ResuFile"〉〈/p〉
〈p〉〈input type="submit" value="提交" name="B1"〉〈/p〉
〈/form〉
〈!-End of post.htm--〉
注意,ENCTYPE關(guān)鍵字一定不能省,否則文件無(wú)法正確上載。
這里,我們?cè)侔严驍?shù)據(jù)庫(kù)插入記錄的代碼重新設(shè)計(jì):
〈?
//begin of file insert.php
if($ResuFile != "none")
//確定用戶選擇了文件
{
$Size = filesize($ResuFile);
//確定文件大小
$mFileData = addslashes(fread(fopen($ResuFile, "r"), $Size));
//讀取文件,對(duì)內(nèi)容進(jìn)行處理
unlink($ResuFile);
//刪除上載臨時(shí)文件
}
$LinkID=@mysql_connect("localhost", "root" , "") or die("不能連接到數(shù)據(jù)庫(kù)服務(wù)器!可能是數(shù)據(jù)庫(kù)服務(wù)器沒(méi)有啟動(dòng),或者用戶名密碼有誤!");
$DBID = @mysql_select_db("ResumeDB",$LinkID) or die("選擇數(shù)據(jù)庫(kù)出錯(cuò),可能是您指定的數(shù)據(jù)庫(kù)不存在!");
$query = "insert into Resume(Name,Intro,ResuFile) values('$Name', '$Intro', '$mFileData')";
$result = @mysql_query("$query",$LinkID); //執(zhí)行查詢,插入文件到數(shù)據(jù)庫(kù)
if(! $result)
echo "數(shù)據(jù)插入失敗!";
else
echo "文件上載成功!";
@mysql_close($LinkID);
//end of file insert.php
?〉
有了上面的基礎(chǔ),寫出從數(shù)據(jù)庫(kù)讀數(shù)據(jù)的程序應(yīng)該很簡(jiǎn)單了。需要注意的是文件向客戶發(fā)送的方法。服務(wù)器必須向?yàn)g覽器發(fā)送頭信息,說(shuō)明將要發(fā)送的數(shù)據(jù)為word文檔。如果用戶計(jì)算機(jī)裝有MSWord,瀏覽器將自動(dòng)調(diào)用word進(jìn)行文檔顯示。
我們可以設(shè)置一個(gè)超級(jí)鏈接,來(lái)下載這個(gè)Word文件:
〈?
//begin of file show.php
$LinkID=@mysql_connect("localhost", "root" , "") or die("不能連接到數(shù)據(jù)庫(kù)服務(wù)器!可能是數(shù)據(jù)庫(kù)服務(wù)器沒(méi)有啟動(dòng),或者用戶名密碼有誤!");