我正在制作一个管理页面,将MySQL中的所有属性和图片上传插入一个文件夹但收到一些错误,这是表格代码
<form role="form" id="form1" action="" enctype="application/x-www-form-urlencoded" method="post">
<div class="col-lg-6">
<div class="form-group">
<label>Title:</label>
<input type="text" name="title" placeholder="enter title" class="form-control"required>
</div>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<label>Image:</label>
<input type="file" name="upload" id="postimage" class="form-control">
</div>
</div>
<input type="reset" name="reset" value="reset">
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Content:</label>
<input type="text" class="form-control" name="content" placeholder="explain in brief">
</div>
<div class="form-group">
<label>Age:</label>
<input type="text" class="form-control" placeholder="enter require age" name="age">
</div>
<div class="form-group">
<input type="submit" name="submitpost" value="Submit-Post" class="form-control">
</div>
</div>
</form>
当我使用PHP代码将我的图像插入一个文件夹名称img和MySQL表中的其他属性时。
<?php
$target_dir = "../../img/";
if (isset($_FILES['upload'])and isset($_POST['submitpost'])) {
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
$title=$_POST['title'];
$age=$_POST['age'];
$content=$_POST['content'];
$query="INSERT INTO `posts`
(`id`,`title`, `image`,`age`, `content`)
VALUES (null,'$title','$target_file','$age','$content')";
if(mysqli_query($con,$query))
{
echo "<script>alert('passed')</script>";
}else{
echo "<script>alert('not passed')</script>";
}
}else{
echo "<script>alert('problem with image upload')</script>";}
}
?>
但提交后我什么都没有,既没有错误也没有任何通知,我不知道什么是问题帮助我,我尝试了一些其他代码,然后插入表格,但图片没有上传到目标文件夹帮助我完成它我是PHP的新手,所以
答案 0 :(得分:1)
您在表单中添加了enctype="application/x-www-form-urlencoded"
进行文件输入,错误。添加如下
<form role="form" id="form1" action="" enctype="multipart/form-data" method="post">
添加 PHP 代码,例如
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/img/';
if(!empty($_FILES['upload']['name'] && isset($_POST['submitpost']))){
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
extract($_POST);
$title = mysqli_real_escape_string($con,$title);
$age = mysqli_real_escape_string($con,$age);
$content = mysqli_real_escape_string($con,$content);
$query = "INSERT INTO `posts` (`id`,`title`,`image`,`age`,`content`)
VALUES (null,'{$title}','{$target_file}','{$age}','{$content}');";
if(mysqli_query($con,$query)){
echo "<script>alert('passed')</script>";
}else{
echo "<script>alert('not passed')</script>";
}
}else{
echo "<script>alert('problem with image upload')</script>";
}
}
请确保$target_dir
是图片上传目录的正确路径。