2

我最近开始学习 Javascript,但仍然不是该主题的专家。
所以我想知道是否有人云帮助我。

我正在使用 MySql 数据库和 PHP 构建一个投资组合网站

我的数据库表有 3 个冒号:name, small_image, description.

我已经设置了我的 PHP,以便它提取namesmall_image.

$name       = htmlentities( $row['name'] );
$image_small    = "images/" . $row['image_small'];

它像这样回响:

$name
< img src='$image_small' with='$width' height='$height' />

我唯一的问题是,当我进入管理页面并在网站上添加一个没有图像的新作品时,它会出现一个空白区域。

我想做的是有一个可以替换丢失图像的图像?

有没有办法让它工作?还是更好、更简单的方法?

对此,我真的非常感激 。

不在这里工作的是完整的代码。

< - - - - - - - - - - - - - - - - - - - 完整代码 - - - - - - - - - - - - - - >

    // Loop through all of the records returned from the query
    while( $row = mysql_fetch_array( $results ) ) {
        // collect data from each field
        $id         = $row['id'];
        $name       = htmlentities( $row['name'] );
        $desc_short     = htmlentities( $row['desc_short'] );           

        if(isset( $row['image_small'])){
            $image_small = "images/jewelry/small/" . $row['image_small'];
        }

        else{
            $image_small = "images/blank.jpg";
        }


echo "

        <li class='column_$x $last_row_class'>
        <a href='details.php?id=$id'>
            <img src='$image_small' with='$width' height='$height' />
        </a>
        <p class='product_name'><a href='details.php?id=$id'>$name</a></p>
        <p class='product_desc'>$desc_short</p>
        $rating_div
        </li>";
4

4 回答 4

1

如果数据库中不存在图像,则应显示空白图像(默认图像)。例如

$name = htmlentities( $row['name'] ); 
if(isSet($row['image_small'])){
         $image_small = "images/" . $row['image_small'];
}
else{
    $image_small = "images/blank.jpg";
}

注意:您应该将blank.jpg 放在您的图像文件夹中。

我建议您在系统文件夹中上传图像时将图像名称保存在数据库中。或者您可以检查文件夹中的图像文件,如下所示:

<?php
$filename = "images/" . $row['image_small'];

if (!file_exists($filename)) {
     $image_small = "images/blank.jpg";
} 
?>

享受!!!!!!!

于 2011-06-03T04:24:07.093 回答
0

尝试将上面第一个代码块中的代码更改为如下所示:

$name         = htmlentities( $row['name'] );
$image_small  = ($row['image_small'] != '') ? "images/" . $row['image_small'] : '/path/to/default.png';

它的作用是检查是否$row['image_small']有值,如果有,则将其用于$image_small,否则设置$image_small为默认小图像的路径。

于 2011-06-03T04:22:30.727 回答
0

除了其他建议,您可以使用 MySQL 中的 ISNULL() 函数返回默认图像名称。例如,在您的 images 目录中创建一个 default.png 图像,并在您的查询中使用它:

SELECT
  name,
  IF(ISNULL(small_image),'default.png',small_image) AS "small_image",
  description
FROM
  images;

并不是说它一定是一个更好的答案,只是一个替代方案。

于 2011-06-03T04:27:29.260 回答
0

客户端解决方案是使用 img 标签的“onerror”属性。这就像:

 <img src='$image_small' with='$width' height='$height' onerror='this.src = "/images/default.jpg" ;' />
于 2011-06-03T06:03:04.797 回答