【发布时间】:2021-09-27 11:24:47
【问题描述】:
我学习php,尝试为自己开发一个小博客。我有一个问题。当我从数据库中提取信息时,除了图片之外的所有内容都显示出来了。在代码中,我尝试将图片保存在 img 文件夹中,数据库中有一个补充,但没有保存到文件夹中。这可能是没有图像输出的原因。 我寻求帮助。对不起我的英语不好。谢谢!
//添加帖子
<?php
session_start();
require_once '../DB.php';
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['button-post'])) {
$error ='';
if (!empty($_FILES['img']['name'])){
$img = time() . "_" . $_FILES['img']['name'];
$fileTmpName = $_FILES['img']['tmp_name'];
$fileType = $_FILES['img']['type'];
$destination = "../img/" . $img;
if (strpos($fileType, 'image') === false) {
$error = "The uploaded file is not an image!!";
}else{
$result = move_uploaded_file($fileTmpName, $destination);
if ($result){
$_POST['img'] =$img ;
// tt( $img);
}else{
$error = " Error uploading image to server";
}
}
}else{
$error= "Error getting picture";
}
$title = trim( $_POST['title']);
$texton = trim( $_POST['texton']);
if (strlen($title) <= 2 ) {
$error = '';
}
elseif (strlen($texton)<= 5 ) {
$error = '';
}
else {
$sql = "INSERT INTO `posts`(`title`, `texton`, `img`) VALUES(?,?,?)";
$query = $connect->prepare($sql);
$query->execute([$title,$texton,$img]);
}
}
//索引
<?php
require_once 'DB.php';
$sql = "SELECT * FROM `posts` ORDER BY`id`DESC";
$query = $connect->query($sql);
while ($row = $query->fetch(PDO::FETCH_OBJ)):
?>
<div class="titlePost col-12 col-md-9">
<h2>
<a href="#"><?=$row->title;?></a>
</h2>
<div class="imgPost col-12 col-md-4">
<img src="/img .<?= $row->img?>;" alt="postik">
</div>
<p> <?=$row->texton;?></p>
</div>
<?php endwhile; ?>
<form action="addPost_form.php" method="post" class="row justify-content-center">
<h2>Add Post</h2>
<div class="mb-3 col-12 col-md-4 err">
<p><?=$error?></p>
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-6">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-8">
<label for="texton">Сontent</label>
<textarea type="text" name="texton" id="texton" class="form-control" ></textarea>
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-4">
<input name="img" enctype='multipart/form-data' type="file" class="form-control" id="img">
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-4">
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-4">
<button type="submit" class="btn btn-secondary" name="button-post">Add</button>
</div>
</form>
【问题讨论】:
-
你能同时显示你上传图片的表格吗
-
您尝试过什么来解决问题?你被困在哪里了?数据库中是否存储了正确的数据?标记是否正确生成?只是缺少文件吗?
-
如果您的图片没有保存在文件夹中,您很可能忘记在表单标签中传递 enctype="mutlipart/form-data" 参数
-
@NicoHaase 坚持图像未显示在屏幕上的事实。文件传输本身是,我用调试功能检查了它。文件名及其扩展名保存在数据库中。但是输出中没有图像。我将添加一个填充表单
-
您已将上传的文件移至
'../img/' . $imgName,但随后您的 HTML 中仅输出了<img src="<?= $row->imgName?>;"。那么../img/部分去哪儿了?