Latest web development tutorials

PHP PDO large objects (LOBs)

PHP PDO Reference Manual PHP PDO Reference Manual

Application at a time, you might need a database to store "large" data.

"Large" usually means "around 4kb or more", although some of the data in the database to achieve "big" before can easily handle up to 32kb of data. It may be text or binary large objects in nature.

() Or PDOStatement :: bindColumn ()) call using the PDO in PDOStatement :: bindParam :: PARAM_LOB PDO type code allows the use of large data types.

PDO :: PARAM_LOB tells PDO to map the data as a stream, in order to be able to use PHP Streams API to operate.

Display an image from a database

The following example is bound to a LOB variable $ lob and then () sends it to the browser with fpassthru. Because LOB represents a stream, so similar to fgets (), fread () and stream_get_contents () function can be used such as on top of it.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?>

Insert an image into a database

The following example opens a file and pass the file handle to PDO to do a LOB inserted. PDO as much as possible so that the database in the most efficient way to get the contents of the file.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // 调用某个函数来分配一个新 ID

// 假设处理一个文件上传
// 可以在 PHP 文档中找到更多的信息

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

Insert an image into a database: Oracle

For inserting a lob from a file, Oracle is slightly different. Must be inserted after the transaction, otherwise cause the newly inserted when the query is executed LOB with 0 length is implicitly submitted:

<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // 调用某个函数来分配一个新 ID

// 假设处理一个文件上传
// 可以在 PHP 文档中找到更多的信息

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>

PHP PDO Reference Manual PHP PDO Reference Manual