我在 MS ACCESS 数据库中有 BLOB 图像。到目前为止,我已经将它们与 PHP 的 odbc Access 一起使用,并且工作正常。简化程序来了:
code:
<?php
ini_set("odbc.defaultlrl", "5M");
$dbName = $_SERVER["DOCUMENT_ROOT"]."\\..\db\\teknofo.mdb";
$con = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=".$dbName,'','') or die('Ups');
ob_clean();
header('Content-Type: image/*');
$sql = "SELECT photo FROM Medlemmer WHERE Id=17";
$rd = odbc_exec($con, $sql);
if (odbc_fetch_row($rd)) { echo odbc_result($rd,"photo"); }
odbc_close($con);
ob_end_flush();
?>
我正在转换为 MySql,但将不得不使用 MS Access 进行一些 timg: 因此,我正在使用 PDO 编写新代码,但无法正确读取数据。
新的来了
<?php
$dbName = $_SERVER["DOCUMENT_ROOT"]."\\..\db\\teknofo.mdb";
$con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");
$sql = "SELECT photo FROM Medlemmer WHERE id=?";
$st = $con->prepare($sql);
$st->execute(array(17));
$st->bindColumn('photo', $photo, PDO::PARAM_LOB);
$st->fetch(PDO::FETCH_BOUND);
odbc_longreadlen($st, 131072);
odbc_binmode($st,ODBC_BINMODE_CONVERT);
ob_clean();
header('Content-Type: image/*');
if ($rd = $st->fetch(PDO::FETCH_BOUND)) {
echo $rd['photo'];
ob_end_flush();
$con = null;
?>
最后的代码适用于 MySql(更改连接字符串)但不适用于 MS Access。
网上找了半天也没找到解决办法。
有人可以帮忙吗?
我可以使用第一个代码,但我还需要能够处理 BLOB 以用于其他目的。
最佳答案
PHP 和 Access ODBC 驱动程序从来都不是最好的 friend ,显然 PDO_ODBC 和 Access ODBC 驱动程序仍然如此。这里的两条皱纹是
BLOB 作为表示图像数据的十六进制值的 ASCII 字符串返回(例如,“424D7AC000...”),并且
该字符串每 255 个字符包含一个虚假的 NULL 字符。
我设法开始工作的代码是:
<?php
$dbName = $_SERVER["DOCUMENT_ROOT"]."\\test.mdb";
$con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");
$sql = "SELECT Photo FROM Clients WHERE id=?";
$st = $con->prepare($sql);
$st->execute(array(1));
$st->bindColumn(1, $photoChars, PDO::PARAM_LOB);
$st->fetch(PDO::FETCH_BOUND);
// $photoChars is a long string of hex, e.g., '424D7A...'
// PDO+Access_ODBC apparently injects a NULL every 255 characters,
// so remove them first
$photoChars = str_replace("\0", "", $photoChars);
// create array of character pairs (e.g.: '42', '4D', '7A', ...)
$photoArray = str_split($photoChars, 2);
// convert to numeric values
for ($i = 0; $i < sizeof($photoArray); $i++) {
$photoArray[$i] = hexdec($photoArray[$i]);
}
// pack into binary string
// ref: http://stackoverflow.com/a/5473057/2144390
$photoData = call_user_func_array("pack", array_merge(array("C*"), $photoArray));
header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_PNG));
header('Content-Disposition: attachment; filename="untitled.bmp"');
echo $photoData;
关于PHP PDO MS Access 如何读取 blob 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22325904/