文件上传到MySQL数据库通常涉及以下几个步骤:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html><?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
} else {
echo "File is not an image.";
}
}
// Store file path in MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO files (filename, filepath) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", basename($_FILES["fileToUpload"]["name"]), $target_file);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$conn->close();
?>原因:
解决方法:
php.ini)中的upload_max_filesize和post_max_size设置。accept属性限制文件类型。原因:
解决方法:
mysqli_error()函数检查SQL语句错误。通过以上步骤和代码示例,你可以实现文件上传并存储到MySQL数据库中。如果遇到具体问题,请根据错误信息进行排查和解决。
没有搜到相关的沙龙