example #1 从数据库中显示一张图片
下面例子绑定一个 lob 到 $lob 变量,然后用 fpassthru() 将其发送到浏览器。因为 lob 代表一个流,所以类似 fgets()、 fread() 以及stream_get_contents() 这样的函数都可以用在它上面。
<?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); ?>
example #2 插入一张图片到数据库
下面例子打开一个文件并将文件句柄传给 pdo 来做为一个 lob 插入。pdo尽可能地让数据库以最有效的方式获取文件内容。
<?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(); ?>
example #3 插入一张图片到数据库:oracle
对于从文件插入一个 lob,oracle略有不同。必须在事务之后进行插入,否则当执行查询时导致新近插入 lob 将以0长度被隐式提交:
<?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(); ?>
