今天教給大家如何用PHP實現把圖象上傳到MYSQL資料庫中。 在這個教程中我們需要建立3個PHP檔案:
readdir.php - 把圖片放到資料庫的代碼
image.php - 顯示實際圖片的代碼
view.php - 顯示你如何調用資料庫中的圖片的代碼
1.建立一個資料庫
CREATE TABLE `images` (
`imgid` INT NOT NULL AUTO_INCREMENT ,
`sixfourdata` LONGTEXT NOT NULL ,
PRIMARY KEY ( `imgid` )
);
READDIR.PHP
具體的內容:
$dbcnx = mysql_connect("localhost", "username", "password");
mysql_select_db("base64imgdb");
?>
'我們需要開啟一個目錄
"./"
'readdir.php 檔案定位於這個目錄:
$path = "./";
$dir_handle = opendir($path) or die("Unable to open directory $path");
下面是比較難的部分,大家需要好好研究一下:把圖象分類,並且讀出正在使用的一些資料
fopen
'轉換
base64_encode
' 插入到表裡
while ($file = readdir($dir_handle)) {
$filetyp = substr($file, -3);
if ($filetyp == 'gif' OR $filetyp == 'jpg') {
$handle = fopen($path . "/" . $file,'r');
$file_content = fread($handle,filesize($path . "/" . $file));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$sql = "INSERT INTO images SET sixfourdata='$encoded'";
mysql_query($sql);
}
}
?>
關閉設定的目錄,然後處理:
closedir($dir_handle);
echo("complete");
mysql_close($dbcnx);
?>
讀出圖片的代碼:IMAGE.PHP
這段代碼比較難,我們要好好看看
$dbcnx = mysql_connect("localhost", "username", "password");
mysql_select_db("base64imgdb");
?>
我們讀出圖片使用的代碼image.php?img=x:
$img = $_REQUEST["img"];
?>
之後我們需要串連資料庫,然後讀出
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $img . "");
if (!$result) {
echo("
請求錯誤: " . mysql_error() . "");
exit();
}
while ($row = mysql_fetch_array($result)) {
$imgid = $row["imgid"];
http://www.bkjia.com/PHPjc/630928.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/630928.htmlTechArticle今天教給大家如何用PHP實現把圖象上傳到MYSQL資料庫中。 在這個教程中我們需要建立3個PHP檔案: readdir.php - 把圖片放到資料庫的代碼 imag...