我正在尝试将文件路径上传到MySQL数据库。 我有这个HTML格式:
<form action="" method="post" name="add_maps" enctype="multipart/form-data">
<table border="1" cellpadding="2" cellspacing="1" align="center" dir="rtl">
<tr>
<th>
name of map</th>
<td>
<input type="text" name="name_of_map"/>
</td>
<th>
select map</th>
<td>
<input type="file" name="file" id="file"/>
</td>
</tr>
<tr>
<input type="submit" name="submit_map" value="upload"/>
</tr>
</table>
</form>
在同一页面中,我有要上传的PHP代码:
<?php
require_once('../include/inner_global.php');
$hostdb = "localhost";
$namedb = "architect";
$userdb = "root";
$passdb = "root";
$id = $_REQUEST['id'];
$name='';
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
$path = "../uploads/".$_FILES['file']['name'];
if(isset($_POST['submit_map'])){
try{
$name = isset($_POST['name']) ? $_POST['name'] : '';
$ext = pathinfo($path, PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path)){
$path = "./uploads/".$path;
$sql = "INSERT INTO maps(name_of_maps, projects_id, map) VALUES (:name, :id, :file)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":name", $name);
$stmt->bindValue(":id", $id);
$stmt->bindValue(":file", $path);
$count = $stmt->execute();
}
}
catch(PDOException $e) {
echo $e->getMessage();
header("location: insert_map_false.php?id=".$id);
}
}
?>
当我转到此html表单所在的页面时,我在标题中直接显示此错误:
P.S
当我点击上传但未添加到数据库时,文件会正确上传到其路径。 的修改
这是我的表数据类型
答案 0 :(得分:1)
首先检查是否发布。在这种情况下添加所有代码,它将解决您的问题:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//All code ....
}
或在以下位置创建hidden input
:
<input type="text" name="id" type="hidden" value="<?php echo $_REQUEST['id']; ?>"/>
我认为问题发生在$id = $_REQUEST['id'];
,因为来自$id
empty
的值为submit
答案 1 :(得分:1)
您的SQL查询是:
$sql = "INSERT INTO maps(name_of_maps, projects_id, map) VALUES (:name, :id, :file)";
但您的专栏是name_of_map
而不是name_of_maps
您的查询应该是这样的:
$sql = "INSERT INTO maps(name_of_map, projects_id, map) VALUES (:name, :id, :file)";