PHP映像未存储在数据库中



所以我有一个表单,它将把标题和内容上传到我的DB。我还有一个文件上传,它会上传图像到我的"img"文件夹,但不会上传到我的数据库。有人能帮我处理代码吗:

editreview.php


if($_SERVER["REQUEST_METHOD"] == "POST") {
$sql = "INSERT INTO reviews (name, content, image)
VALUES('" . $_POST['name'] . "',
'" . $_POST['content'] . "',
'" . $_POST['image'] . "')";
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}

if ($conn->query($sql) && empty($errors) === TRUE) {
echo "New record created successfully";
move_uploaded_file($file_tmp,"img/".$file_name);
header('location: index.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?> ````
review.php
````</main>
<h2>Leave a review</h2>
<form method = "post" enctype="multipart/form-data">
Name: <input type="text" name="name">
Comment: <textarea name="content" rows="5" cols="40"> </textarea>
<input type="file" name="image" />
<button>Add Review</button>

Anyone know why the image is not posting/storing into my DB yet my title and content are directly storing to the database. I find it strange that my image is also storing into my images folder but not the main Database. 

上传只会将文件存储在Web服务器的文件系统中。

位置将为$_FILES['image']['tmp_name']

您已经使用move_uploaded_file()将临时文件移动到'img/' . $file_name

你想做的是:

  1. 打开位于$_FILES['image']['tmp_name']的文件
  2. 阅读其内容
  3. 将其转换为您喜欢的格式来报道数据
  4. 然后将数据写入SQL语句

例如:

$sql = "INSERT INTO reviews (name, content, image)
VALUES('" . $_POST['name'] . "',
'" . $_POST['content'] . "',
'" . base64_encode(file_get_contents($_FILES['image']['tmp_name'])) . "')";

您在sql查询中使用了$_POST['image'],但需要使用$_FILES['image']['name']。因此,使用以下代码更改您的sql查询

$sql = "INSERT INTO reviews (name, content, image)
VALUES('" . $_POST['name'] . "',
'" . $_POST['content'] . "',
'" . $_FILES['image']['name'] . "')";

最新更新