PDO检索和显示图像而无需创建文件 [英] PDO to retrieve and display images without creating files
问题描述
试图遍历带有图像的测试数据库(我知道很多人不这样做,但是在备份等方面大大简化了).我可以通过动态创建图像文件来获得所需的结果,但是必须有一种无需创建文件即可执行此操作的方法.有人可以建议不用创建这些图像文件就可以使用的语法吗?
Trying to loop through a test database with images (I know many say not to do this, but it simplifies so much in terms of backups, etc.). I can get the result I want by creating image files on the fly, but there must be a way to do this without creating files. Can someone suggest a syntax I can use without having to create these image files?
这是我的工作:
<?php
// configuration
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "SELECT id,title,author,description,cover FROM books";
$q = $conn->prepare($sql);
$q->execute();
$q->bindColumn(1, $id);
$q->bindColumn(2, $title);
$q->bindColumn(3, $author);
$q->bindcolumn(4, $description);
$q->bindColumn(5, $cover, PDO::PARAM_LOB);
while($q->fetch())
{
file_put_contents($id.".png",$cover);
echo ("<img src='".$id.".png'><br />, $title, $author, $description,<br/>");
}
?>
我认为我们应该能够消除"file_put_contents .."行,并在回显行中替换
I am thinking that we should be able to eliminate the "file_put_contents.." line and in the echo line, replace the
<img src='".$id.".png'>"
带有一些php/pdo语句,该语句检索blob并将其放置为正确的格式.尝试了几件事,但没有成功.
with some php/pdo statement that retrieves the blob and puts it in the proper format. Tried a few things, but have not been successful.
任何建议都会有所帮助!
Any suggestions would be helpful!
推荐答案
您不需要在2个单独的文件中执行此操作,而无需在img标签的src属性中调用脚本.
you do not need to do it in 2 separate files and invoke the script in src attribute of img tag.
尝试执行此操作
echo '<img src="data:image/'.$type.';base64,'.base64_encode($image).'"/>';
其中$ type是图像的扩展名(.png/.jpeg/....),$ image是您存储在数据库中的图像的二进制文件.就我而言,我从数据库中提取图像类型的值,如果您始终存储相同的扩展名(例如jpeg),则可以简单地写:
Where $type is the extension of the image(.png/.jpeg/....) and $image is the binary of the image that you have stored in your DB. in my case I pull the value of the type of image from the db, if you store always the same extension(ex jpeg) you can simply write:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
该方法是使用2个文件的替代方法.
the method is an alternative to do that with 2 files.
这篇关于PDO检索和显示图像而无需创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!