猿问

通过数据库中的链接显示图像?(PHP/MYSQLI) 新手

如果我在数据库中存储指向图像的链接然后只在网站上显示它们可以吗?这是一种不好的做法吗?下面的示例代码

<?
  echo "<img src='/projects".$row['image']."' >";


梵蒂冈之花
浏览 186回答 1
1回答

holdtom

按照评论的要求。根据您的应用程序及其复杂性,您可能希望尽可能简化图像加载,并且将图像 url 存储在数据库中并不是最好的方法。理想情况下,您希望按类型将图像分组到目录中,并保持图像名称的通用结构,以便您只需替换 thair id 或单个字符串即可轻松交换图像。这是一个非常简化的图像加载器类的示例:目录结构:images&nbsp; &nbsp; -> products&nbsp; &nbsp; &nbsp; &nbsp; -> product-123.png&nbsp; &nbsp; -> icons&nbsp; &nbsp; &nbsp; &nbsp; -> arrow.png图像加载器类:class ImageLoader {&nbsp; &nbsp; const IMAGE_PATH = '/images'&nbsp; &nbsp; const PROCUCT_IMAGE_PATH = '/products/'&nbsp; &nbsp; const ICON_IMAGE_PATH = '/icons'&nbsp; &nbsp; const IMAGE_EXTENSION = '.png'&nbsp; &nbsp; static public function getIconImage($identifier) {&nbsp; &nbsp; &nbsp; &nbsp; return self::IMAGE_PATH&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . self::ICON_IMAGE_PATH&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . $identifier&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . self::IMAGE_EXTENSION;&nbsp; &nbsp; }&nbsp; &nbsp; static public function getProductImage($identifier) {&nbsp; &nbsp; &nbsp; &nbsp; return self::IMAGE_PATH&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . self::PROCUCT_IMAGE_PATH&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . 'product-'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . $identifier&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . self::IMAGE_EXTENSION;&nbsp; &nbsp; }}用法手动传递图像名称:<img src="<?= ImageLoader::getIconImage('arrow') ?>" />传递一个变量作为 id 存储在数据库中:<img src="<?= ImageLoader::getProductImage($productIdFromDatabase) ?>" />
随时随地看视频慕课网APP
我要回答