-2

这是我的代码(将新闻添加到数据库中)。

if(!empty($_FILES['img']['name'])){
    $extension = end(explode(".",$_FILES['img']['name']));

    $name = $_FILES['img']['name'];
    $size = $_FILES['img']['size'];

    if(file_exists("views/admin/uploads/".$name)){
        $errors[] = "File with this name already exists!";
    }

    if($extension != "jpg" && $extension != "png" && $extension != "gif" && $extension != "JPG"){
        $errors[] = "Unknown file format!";
    }
}

if(count($errors)==0){
    $query = mysql_query("INSERT INTO `avetisyan`.`$category` (`id`, `category`, `sub_category`, `news_category`, `title`, `img`, `short_content`, `content`, `date`, `lang`) VALUES (NULL, '$category', '$sub_category', '$news_category', '$title', '$name', '$short_content', '$long_content', '$date', '$lang')");
    move_uploaded_file($_FILES['img']['tmp_name'],"views/admin/uploads/".$name);
    echo "<h2 align=\"center\">Successfully added!</h2>";
}
else{
    print "<h3>Errors!</h3><ul><li>".join("</li><li>",$errors)."</li></ul>";
}

如您所见,图像的名称进入数据库,图像进入 /views/admin/uploads/..

在新闻中显示此图像的正确方法是什么?如何?

4

5 回答 5

1

move_uploaded_file($_FILES['img']['tmp_name'],"views/admin/uploads/".$name);

您可以在配置文件中有这个“views/admin/uploads”并从配置中获取它,然后在上传文件时与图像文件名“$name”'连接

有一个提供图像路径的单独函数,在您的情况下为“/views/admin/uploads”从数据库中检索数据并循环结果以获取完整的图像路径

于 2013-06-19T09:53:59.657 回答
0

执行查询以获取所有记录,遍历记录并执行类似的操作

<?php
    $query = mysql_query("SELECT * FROM  `table_name`");

    if(mysql_num_rows($query) > 0)
    {
        for($i=0; $i<mysql_num_rows($query); $i++)
        {
            $row = mysql_fetch_array($query);
            echo '<img src="views/admin/uploads/'.$row['img'].'" />';
        }
    }
?>

边注:

mysql extension is deprecated as of PHP 5.5.0, and will be removed in the future. 
Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an 
API guide and related FAQ for more information. Alternatives to this function include:
于 2013-06-19T09:49:51.073 回答
0
<?php $name = getImageNameFromDB(); ?>
<img src="<?php echo $name; ?>"/>

强制性说明: mysql_* 方法已弃用,不应使用。此外,您的代码可能容易受到SQL 注入攻击。考虑过滤您输入的内容,甚至更好,切换到准备好的语句。

于 2013-06-19T09:50:24.910 回答
0
<?php
$image_query = 'select * from `avetisyan`.`$category`';
$img = mysql_query($image_query );
while($get_items = mysql_fetch_array($img ))
{
    echo '<div id="images">';
    echo '<b>'.$get_items['title'].'</b>';
    echo '<br><img src="uploads/'.$get_items['img'].'">';
    echo '</div>';
}
?>

使用上面的代码使用适当的 css 样式来显示图像

于 2013-06-19T09:51:02.577 回答
0

您从数据库中获取名称并将其作为标记中的源回显。例如,如果您正在显示类别 $category 中的简短新闻文章列表及其图像(在非常简约的布局中):

$res = mysql_query("SELECT * FROM avetisyan".$category);

echo("<table>");

while ($row = mysql_fetch_assoc($res)) {
    echo("<tr>");
    echo("<td>");
    echo("<img src=\"views/admin/uploads/".$row['img']."\">");
    echo("</td>");
    echo("<td>");
    echo($row['short_content']);
    echo("</td>");
    echo("</tr>");
}

echo("</table>");
于 2013-06-19T10:16:58.373 回答