怎么使用PDO来操作bytea

2025-09-22 07:01:52

1、新建一个数据库的表,叫做blobstore

create table blobstore(   id serial primary key,   doc varchar,   blob bytea);

2、创建一个php文件,输入下面的文本

<?php  $dsn = 'pgsql:dbname=test;host=127.0.0.1';  $user = 'user';  $password = 'password';    // these variables must be set to match the actual connection  try {    $dbh = new PDO($dsn, $user, $password);  } catch (PDOException $e) {    die('Connection failed: ' . $e->getMessage());  }  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

3、保存到bytea的代码为:

$data = bin2hex(file_get_contents($filename));

 try{     $sql="insert into blobstore (doc,blob) values('test',?)";    $sqlh= $dbh->prepare($sql);    $sqlh->execute(array($data));  }  catch(Exception $e){    die($e->getMessage());  }  print("<p>Done</p>");

4、添加读取bytea的代码:

 $sql="select blob from cddoc where id=?";  $sqh=$dbh->prepare($sql);  $sqh->execute(array($_GET['id']));  $data=$sqh->fetchAll(PDO::FETCH_NUM);  $data=$data[0][0]; // print($data) here will just return "Resource id # ..."  header('Content-Type: image/png'); // must be adjusted accordingly for other file types, maybe filetype stored as a field in the table?  $data=fgets($data); // The data are returned as a stream handle gulp all of it in in one go, again, this may need some serious rework for too large files   print(pack('H*',$data));

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢