PHP PDO Large Objects (LOBs)
At some point, an application may need to store "large" data in the database.
"Large" usually means "about 4kb or more", although some databases can easily process up to 32kb of data before it reaches "Large". Large objects may be text or binary in nature.
existPDOStatement::bindParam()
orPDOStatement::bindColumn())
Using the PDO::PARAM_LOB type code in the call allows PDO to use big data types.
PDO::PARAM_LOB tells PDO to map data as a stream so that it can be operated using the PHP Streams API.
Display an image from the database
The following example binds a LOB to the $lob variable, and then usesfpassthru()
Send it to your browser. Because LOB represents a stream, it's similarfgets()
、fread()
as well asstream_get_contents()
Such functions can be used on 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 the database
The following example opens a file and passes the file handle to the PDO to insert it as a LOB. PDO allows the database to obtain file contents in the most efficient way possible.
<?php $db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2'); $stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)"); $id = get_new_id(); // Call a function to assign a new ID// Suppose that a file is processed// More information can be found 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(); ?>
Insert an image into the database: Oracle
Oracle is slightly different for inserting a lob from a file. Insert must be done after the transaction, otherwise the newly inserted LOB will be implicitly committed with 0 length when the query is executed:
<?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(); // Call a function to assign a new ID// Suppose that a file is processed// More information can be found 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(); ?>
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below