【发布时间】:2025-12-15 17:25:01
【问题描述】:
我试图将图像插入服务器文件夹,然后将路径插入数据库,但我可以将文件上传到服务器文件夹,无法将任何东西存储到数据库中,例如文件类型、文件大小和文件名(我的意思是路径)。我是 php 新手,请尝试帮助我。
使用php和mysql
index.php
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
上传.php
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
$smt=$db->prepare($sql);
$smt->execute();
view.php
<table width="80%" border="1">
<tr>
<th colspan="4">your uploads...<label><a href="index.php">upload new files...</a></label></th>
</tr>
<tr>
<td>File Name</td>
<td>File Type</td>
<td>File Size(KB)</td>
<td>View</td>
</tr>
<?php
$sql="SELECT * FROM tbl_uploads";
$result=$db->query($sql);
while($row=$result->fetch_object())
{
?>
<tr>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['size'] ?></td>
<td><a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a></td>
</tr>
<?php
}
?>
</table>
表格详情 enter image description here
CREATE TABLE `tbl_uploads` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`file` varchar(100) NOT NULL,
`type` varchar(10) NOT NULL,
`size` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
【问题讨论】:
-
尝试回应您的查询。并告诉你遇到了哪个错误。
-
你有什么错误吗?
-
文件插入成功没有错误但是任何信息都没有存储在数据库中
-
@TarangP 我已经完成了,但没有错误。
-
您的查询是否正确?尝试使用此查询直接将数据库插入 MySQL 数据库。检查这是否有效。此外,回显所有 3 个变量以查看它们是否具有您需要的正确值。