【问题标题】:How to show an image from a database using PHP and twig如何使用 PHP 和 twig 显示数据库中的图像
【发布时间】:2016-04-15 20:28:14
【问题描述】:

我正在尝试使用 PHPtwig 显示来自数据库的图像。我很难做到这一点。在我的index.twig 中有这行代码:<a><img class="images" src="showImg.php?id={{ text.getImage() }}" /></a>{{ text.getImage() }} 来自for-loopshowImg.php 将根据给定的ID 参数执行选择图像的查询。 在我的showImg.php

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $sql = "SELECT filename, mime, code FROM Img_col WHERE id = :id";
    $stmt = $this->db->prepare($sql);
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    while($row = $stmt->fetchObject('Image')) {
        $this->result[] = $row;
    }
    Header("Content-type: $img->getMime()");
    Header("Content-Disposition: filename=\"$img->getFileName()\"");
    $img->hentCode();
}

我的第一个问题是 IDE 在$stmt = $this->db->prepare($sql); 行中停止,我的第二个问题是如何将图像(code)发送到index.twig。 任何可以帮助我的想法或提示都非常感谢。我愿意接受任何建议

【问题讨论】:

    标签: php mysql symfony twig


    【解决方案1】:

    我不确定你想要实现什么,但这可以在 Symfony 中快速完成。你需要一个控制器来根据路由创建你的响应:

    /**
     * @Route("/image/{id}", name="image")
     */
    public function imageAction($id)
    {
        $image =  $this->getDoctrine()->getRepository('AppBundle:Image')->findOneBy(array('id'=> $id));  
        return $this->render('image.html.twig', array('image' => $image));
    }
    

    显然,您需要在 AppBundle 中创建一个简单的 Image 类,其中至少包含两个字段:id 和 imageName。

    在你的 image.html.twig 中:

    <img src="/images/{{ image.imageName }}"/>
    

    查看文档了解更多信息: Symfony Documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2015-06-21
      相关资源
      最近更新 更多