沃梦达 / 编程问答 / php问题 / 正文

PHP:使用 PDO 从 MySQL 检索图像

PHP: Retrieve image from MySQL using PDO(PHP:使用 PDO 从 MySQL 检索图像)

本文介绍了PHP:使用 PDO 从 MySQL 检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一些旧代码,包括重写基本的 mysql 查询以使用 PDO.

I am refactoring some old code, including rewriting basic mysql queries to use PDO.

以下适用于所有浏览器和所有图像类型:

The following works brilliantly in all browsers and for all image types:

$query = 'SELECT image FROM image WHERE imageid=' . $image_id;
$result = mysql_query($query, $db_conn); querycheck($result);
header("Content-type: image");
echo mysql_result($result, 0);

不幸的是,尽管我使用 PDO 重写了它,但它不起作用.我已经浏览了整个 PDO 文档和标准的网络搜索,但没有任何建议/解决方案有效.

Unfortunately, however I rewrite it using PDO, it doesn't work. I've been through the entire PDO documentation and the standard web search, but none of the advice/solutions work.

如何使用 PDO 从 MySQL 中轻松获取图像并显示它?

How can one easily fetch and image from MySQL using PDO and display it?

编辑 1:

Matthew Ratzloff 给出了下面应该是显而易见的答案,但它不起作用.这是我使用 PDO 测试的实际代码(我尝试了许多变体/参数):

Matthew Ratzloff gives what should be the obvious answer below, but it does not work. Here is the actual code that I test using PDO (and I have tried many variants/parameters):

$connectstring_temp = 'mysql:host=' . $A . ';dbname=' .$B;
$dbh_temp = new PDO($connectstring_temp, $login, $password);
#$dbh_temp->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#$dbh_temp->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);

$sql = "SELECT image FROM image WHERE imageid=" . $image_id;
$query = $dbh_temp->prepare($sql);
$query->execute();

$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;

我保留了相同的语法,但最终代码 $image_id 需要作为参数传递.上面的代码不起作用.PDO 适用于所有类型的所有其他查询.

I've kept the same syntax, although for the final code $image_id needs to be passed as a parameter. The code above does NOT work. PDO works fine for all other queries of all types.

推荐答案

需要参数化imageid值并将参数绑定到PDO::PARAM_LOB:

You need to paramaterize the imageid value and bind the parameter to PDO::PARAM_LOB:

$sql = "SELECT image FROM image WHERE imageid=:id";
$query = $db_conn->prepare($sql);
$query->execute(array(':id' => $image_id));

$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;

当然,您还需要指定完整、正确的内容类型(例如,图像/png).

Of course, you'll also want to specify the complete, correct content type (e.g., image/png).

这篇关于PHP:使用 PDO 从 MySQL 检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP:使用 PDO 从 MySQL 检索图像

基础教程推荐