我正在尝试将图像上传到MySQL中的文件夹和路径。但是,当我尝试时会出错。
形式如下:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" name="caption" /><br/><br />
<input type="file" name="name" /><br />
<input type="submit" id="upload" value="submit" />
</form>
这是upload.php
<?php
define('MAX_FILE_SIZE', 2000000);
$permitted = array('image/jpeg', 'image/jpeg', 'image/png', 'image/gif');
if (isset($_POST['upload'])) {
$caption = $_POST['userfile']['caption'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = "upload/" . $myFile;
if (in_array($fileType, $permitted) && $fileSize > 0
&& $fileSize <= MAX_FILE_SIZE) {
$result = move_uploaded_file($tmpName, $path);
if (!$result) {
echo "Error uploading image file";
exit;
} else {
$db = new mysqli("localhost", "root", "", "image");
if (mysqli_connect_errno()) {
printf("Connect failed: %s<br/>", mysqli_connect_error());
}
$query = "INSERT INTO images (caption, name, size, type, file_path) VALUES (?,?,?,?,?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("siss",$caption, $myFile, $fileSize, $fileType, $path);
if (!$conn->execute()) {
echo 'error insert';
} else {
// echo "<img src=\"upload/'". $myFile .\"'/>";
header("Location: index.php");
}
} else {
die("Error preparing Statement");
}
}
} else {
echo 'error upload file';
}
} else {
echo 'error'; **<==== I get this error**
}
?>
我得到的错误是最后一个Else / echo“错误”。我不知道可能是什么问题。
编辑://
现在可以成功地将图像插入数据库,但是不插入名称和路径吗?
最佳答案
您的PHP代码具有
if (isset($_POST['upload'])) {}
但是在表单中没有所谓的上载,因此将提交按钮添加为
<input type="submit" id="upload" name="upload" value="submit" />
提交按钮需要您缺少的名称。
也关于通知
您应该在PHP文件中添加类似内容
$caption = $_POST['caption'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
和
<input type="file" name="name" /><br />
需要更改为
<input type="file" name="userfile" /><br />
关于php - 上载表格无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21261370/