問(wèn)題描述
我正在重構(gòu)一些舊代碼,包括重寫基本的 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 重寫了它,但它不起作用.我已經(jīng)瀏覽了整個(gè) PDO 文檔和標(biāo)準(zhǔn)的網(wǎng)絡(luò)搜索,但沒(méi)有任何建議/解決方案有效.
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 給出了下面應(yīng)該是顯而易見(jiàn)的答案,但它不起作用.這是我使用 PDO 測(cè)試的實(shí)際代碼(我嘗試了許多變體/參數(shù)):
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;
我保留了相同的語(yǔ)法,但最終代碼 $image_id 需要作為參數(shù)傳遞.上面的代碼不起作用.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.
推薦答案
需要參數(shù)化imageid值并將參數(shù)綁定到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;
當(dāng)然,您還需要指定完整、正確的內(nèi)容類型(例如,圖像/png).
Of course, you'll also want to specify the complete, correct content type (e.g., image/png).
這篇關(guān)于PHP:使用 PDO 從 MySQL 檢索圖像的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!