PHP:使用PDO从MySQL检索图像 [英] PHP: Retrieve image from MySQL using PDO

查看:154
本文介绍了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文档和标准Web搜索,但没有一个建议/解决方案有效。

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检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆