我能够上传多个图像到上传文件夹和它的路径到数据库,但我的代码是创建新的行在数据库中的每个图像与新的id(我不想)。我想将所有图像的路径存储到数据库中具有相同ID的单个列中,并用逗号分隔。
下面是我的PHP代码:
<?php
include('connection.php');
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$path = 'uploads/';
$path = $path . basename( $explode[0] . time() .'.'. $ext);
$sql="INSERT into pictures (FILE_NAME, FILE_SIZE, FILE_TYPE )
VALUES('$name','$size','$type'); ";
mysqli_query($conn, $sql);
$errors = array();
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','jpeg','gif','bmp','png');
$max_size = 2000000; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
if(!file_exists('uploads')) {
mkdir('uploads', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<p>The file <b>'.$name.'</b> successful upload</p>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
?>
数据库截图如下
2条答案
按热度按时间h7appiyu1#
只需改进代码,并将插入查询放在foreach循环之外即可
我想这会对你有帮助。
ttygqcqt2#