开发者社区> 问答> 正文

如何使用PHP从MySQL数据库存储和检索图像?

如何在MySQL中插入图像,然后使用PHP检索图像?

我在这两个领域的经验都很有限,我可以使用一些代码让我着手解决这个问题。

展开
收起
保持可爱mmm 2020-05-10 18:50:07 799 0
1 条回答
写回答
取消 提交回答
  • 首先,您创建一个MySQL表来存储图像,例如:

    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 '' ); 然后,您可以将图像写入数据库,如下所示:

    /*** * 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); 您可以使用以下方法在网页中显示数据库中的图像:

    $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);来源:stack overflow

    2020-05-10 18:50:22
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
2022 DTCC-阿里云一站式数据库上云最佳实践 立即下载
云时代的数据库技术趋势 立即下载
超大型金融机构国产数据库全面迁移成功实践 立即下载

相关镜像