PHP PDO Large Objects (LOBs)
At some point, an application may need to store "large" data in a database.
"Large" usually means "about 4kb or more", although some databases can easily handle up to 32kb of data before it becomes "large". A large object can essentially be text or binary.
Using the PDO::PARAM_LOB type code in a PDOStatement::bindParam() or PDOStatement::bindColumn() call lets PDO use the large data type.
PDO::PARAM_LOB tells PDO to map the data as a stream so that it can be manipulated using the PHP Streams API.
Displaying an Image from the Database
The example below binds a LOB to the $lob variable, then sends it to the browser with fpassthru(). Because a LOB represents a stream, functions like fgets(), fread(), and stream_get_contents() can all be used on it.
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);
?>
Inserting an Image into the Database
The example below opens a file and passes the file handle to PDO to insert as a LOB. PDO lets the database fetch the file content in the most efficient way possible.
prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // 调用某个函数来分配一个新 ID
// Assuming processing a file upload
// Find more information in the PHP documentation
$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();
?>
Inserting an Image into the Database: Oracle
Inserting a lob from a file is slightly different in Oracle. The insert must be done within a transaction, otherwise when the query is executed the newly inserted LOB will be implicitly committed with a length of 0:
prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // 调用某个函数来分配一个新 ID
// Assuming processing a file upload
// Find more information in the PHP documentation
$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