2

作为一种好的做法,我只将图像的链接存储在我的数据库中,问题是:

我应该如何存储我的图像的链接?(假设它在 c 上:)

c://image.jpg ?

我应该使用哪种 PHP 代码来显示该图像?我只显示路径,我应该怎么做才能显示图像?

我可以使用这个:

$query = "SELECT ImageURL from WhateverTable";

$result = mysql_query($query) or die(mysql_error());

$Image = mysql_fetch_row($result);

echo "<img src='$Image[0]' alt='This is an image'>";

谢谢各位小伙伴

4

3 回答 3

3

您只想存储相对路径,而不是绝对路径,因为链接到类似

 <img src="/var/www/vhosts/website.com/images/file.jpg"> 

将在任何真实网站上返回 404。通过相对路径 (/images/file.jpg) 将文件存储在数据库中,如果它们都在同一目录中,则仅通过文件名存储。

或者,您可以学习 MongoDB,它允许您将文件实际存储在数据库本身中。

于 2013-02-24T20:45:10.663 回答
2
  1. 我强烈建议您改用 PDO。
  2. 使用图像文件夹的相对 URL,以备有一天需要移动它们。

这是一个例子。

// relative to your public webroot
$publicImageUrl = '/images/in/here';

// Pull up some record, maybe of a product 
$select = 'SELECT imageFilename FROM products WHERE id = 2332';
$results = mysql_query($select);
if(!$results) {
    // issue with query. deal with it here
} else {
    if( mysql_num_rows($result) ) {
        // record not found. deal with it here
    }

    $row = mysql_fetch_array($result);

    $imageSrc = $publicImageUrl  . '/' . $row['imageFilename'];
}

然后你的 HTML 如下

<img src="<?php echo $imageSrc; ?>" />
于 2013-02-24T21:42:20.563 回答
0
  1. 使用PDO进行 php <-> mysql 连接

  2. 发布mysql查询输出

于 2013-02-24T20:43:29.727 回答