PHP 来自 sql 的图片名称未加载

PHP picture name from sql not loading

我有一个正在使用的 PHP 购物车。我将所有图片都存储在项目的文件夹 url 目录中。在我的 SQL 数据库中,我有一个包含所有图像名称的图像 table。当我用 php 加载图片名称时,它会以某种方式向目录路径添加一些额外的随机字符: /img/%7B$row_product_image[名称]%7D 404(未找到) 如果我硬编码图像目录 img/picturename.jpg 就可以了。 这是我的。

<?php
include_once "objects/database.php";
include_once "objects/product.php";
include_once "objects/product_images.php";
// object instances
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
$product_image = new ProductImage($db);
$recordsPerPage = 1;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    echo '<div class="col-md-4 mb-2">';
        echo '<div class="product-id d-none">{$id}</div>';
            echo '<a href="product.php?id={$id}" class="product-link">';
                $product_image->product_id = $pid;
                $stmt_product_image = $product_image->readFirst();
                while($row_product_image = $stmt_product_image->fetch(PDO::FETCH_ASSOC)) {
                    echo '<div class="mb-1">';
                        echo '<img src="img/{$row_product_image[name]}" class="w-100" />';
                    echo '</div>';
                }
                echo '<div class="product-name mb-1">{$name}</div>';
            echo '</a>';

    echo '</div>';
}
class ProductImage {
    private $pdoConn;  private $table_name = "product_images";
    public $id;
    public $product_id;
    public $name;
    public $timestamp;
    public function __construct($dbconn) {
        $this->pdoConn = $dbconn;
    }
    function readFirst() {
        // SELECT query
        $query = "SELECT id, pid, name " .
                 "FROM " . $this->table_name . " " .
                 "WHERE pid = ? " .
                 "ORDER BY name DESC " .
                 "LIMIT 0, 1";
        // prepare query statement
        $stmt = $this->pdoConn->prepare($query);
        // sanitize
        $this->product_id=htmlspecialchars(strip_tags($this->product_id));
        // bind variable as parameter
        $stmt->bindParam(1, $this->product_id);
        // execute query
        $stmt->execute();
        // return values
        return $stmt;
    }
}
?>
while($row_product_image = $stmt_product_image->fetch(PDO::FETCH_ASSOC)) {
                echo '<div class="mb-1">';
                echo '<img src="img/'.$row_product_image['name'].'" class="w-100" />';
                echo '</div>';
            }

试一试

echo '<img src="img/{$row_product_image[name]}" class="w-100" />';
如果使用单引号 (docs). Also you need to quote "name" string to use it as array index (docs) 引用字符串,

PHP 将不会扩展变量。

就是说,要么通过避免单引号来解决这个问题(但这很难看,所以不要):

echo "<img src=\"img/{$row_product_image['name']}\" class=\"w-100\" />";

阅读起来不那么痛苦:

echo '<img src="img/' . $row_product_image['name'] . '" class="w-100" />';

甚至使用 printf() 来避免将字符串拼成意大利面条:

printf('<img src="img/%s" class="w-100" />', $row_product_image['name']);

试试这个代码: