使用foreach通过PHP和MySQL上传多张图片的步骤如下:
以下是一个示例代码:
HTML页面(upload.html):
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
PHP文件(upload.php):
<?php
// 连接到MySQL数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 处理上传的文件
if(isset($_FILES['files'])){
$errors = [];
$uploadedFiles = [];
$extension = ['jpg', 'png', 'gif'];
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $_FILES['files']['name'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$key])));
$file = 'uploads/' . $file_name;
if(in_array($file_ext, $extension) === false){
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if($file_size > 2097152){
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if(empty($errors)){
move_uploaded_file($file_tmp, $file);
$uploadedFiles[] = $file;
// 将上传的图片信息插入到数据库
$stmt = $conn->prepare("INSERT INTO images (filename, filepath) VALUES (?, ?)");
$stmt->execute([$file_name, $file]);
}
}
if($errors){
print_r($errors);
}
if($uploadedFiles){
echo "Files uploaded successfully:";
foreach($uploadedFiles as $file){
echo "<br>" . $file;
}
}
}
?>
注意:上述示例中的数据库连接信息和表名需要根据实际情况进行修改。
推荐的腾讯云相关产品:腾讯云对象存储(COS),用于存储上传的图片文件。您可以在腾讯云官网上查找更多关于腾讯云对象存储的详细信息和产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云