Trước tiên, bạn tạo một bảng MySQL để lưu trữ hình ảnh, ví dụ như:
create table testblob (
image_id tinyint(3) not null default '0',
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_ctgy varchar(25) not null default '',
image_name varchar(50) not null default ''
);
Sau đó, bạn có thể viết một hình ảnh vào cơ sở dữ liệu như:
/***
* All of the below MySQL_ commands can be easily
* translated to MySQLi_ with the additions as commented
***/
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli
// $link = mysqli_connect("localhost", $username, $password,$dbname);
$sql = sprintf("INSERT INTO testblob
(image_type, image, image_size, image_name)
VALUES
('%s', '%s', '%d', '%s')",
/***
* For all mysqli_ functions below, the syntax is:
* mysqli_whartever($link, $functionContents);
***/
mysql_real_escape_string($size['mime']),
mysql_real_escape_string($imgData),
$size[3],
mysql_real_escape_string($_FILES['userfile']['name'])
);
mysql_query($sql);
Bạn có thể hiển thị một hình ảnh từ cơ sở dữ liệu trong một trang web với:
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);
tôi cũng khuyên bạn nên suy nghĩ điều này qua và sau đó chọn lưu trữ hình ảnh trong hệ thống tệp của bạn thay vì DB .. xem tại đây: http://stackoverflow.com/questions/3748/storing-images-in-db -yea-or-nay –