【发布时间】:2018-09-11 08:30:05
【问题描述】:
我的网站上有一个 cmets 区域。它显示默认图像,然后显示人员评论。我想设置表单,以便当一个人发送评论时,他们可以选择将自己的小图像上传到图像文件夹。当表单发送时,我希望 image_path 记录填充图像在图像文件夹中的位置。即图像/myphoto.jpg 这是表格
<form method="post" enctype="multipart/form-data" class="comment-form" action="form-post.php">
<table class="submit-table">
<tr>
<td><p>First Name:</p></td>
<td><input type="text" name="First" /></td>
</tr>
<tr>
<td><p>Last Name</p></td>
<td><input type="text" name="Last" /></td>
</tr>
<tr>
<td><p>Your Comment: </p></td>
<td><textarea name="Comment" rows="10" cols="60"></textarea></td>
</tr>
<tr>
<td><input type="file" name="image_path" accept=".jpeg,.jpg,.png" />
<p>Feel free to upload a small photo of yourself (Optional)</p>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" class="btn btn-primary" value="submit"/></td> <td>All Comments are moderated and will be posted once approved.</td>
</tr>
</table>
</form>
这里是表单处理程序
<?php
//$sql = "SELECT ID, firstname, Comment, Image_path FROM comment";
//
//$result = $conn->query($sql);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = $_POST["First"];
$lastname = $_POST["Last"];
$comment = $_POST["Comment"];
$imagepath = $_POST["image_path"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO comment (Comment, firstname, lastname, Image_path, Approved)
VALUES ('$comment', '$firstname','$lastname','$imagepath','2')";
if ($conn->query($sql) === TRUE) {
echo "<h4>Thankyou - We have received your comment.</h4>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["image_path"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
if ($target_file == "upload/") {
$msg = "cannot be empty";
$uploadOk = 0;
} // Check if file already exists
else if (file_exists($target_file)) {
$msg = "Sorry, file already exists.";
$uploadOk = 0;
} // Check file size
else if ($_FILES["image_path"]["size"] > 5000000) {
$msg = "Sorry, your file is too large.";
$uploadOk = 0;
} // Check if $uploadOk is set to 0 by an error
else if ($uploadOk == 0) {
$msg = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["image_path"]["tmp_name"], $target_file)) {
$msg = "The file " . basename($_FILES["image_path"]["name"]) . " has been uploaded.";
}
}
}
$conn->close();
?>
我已将信息上传到数据库并将图像上传到图像文件夹,但文件未链接到图像路径。有人可以告诉我该怎么做。谢谢。
【问题讨论】:
-
使用该值添加表单属性 -
enctype="multipart/form-data" -
感谢您的链接。我知道这本身会上传文件,但它不会将路径放在 image_path 数据库列中,用于提交的每条记录。我一定会添加的属性。谢谢
标签: php sql forms file-upload