我正在尝试上传图片到数据库mysql。但我有一个问题,当我试图上传一个图像,图像插入两次。
例如:我有“a.jpg”如果我试图上传它
插入的数据将类似于“a.jpg,a.jpg”
在数据库“a.jpg”中我想要什么
如果我尝试上传多张图片,比如“a.jpg,b.jpg和c.jpg”
插入的数据将类似于“b.jpg,b.jpg,c.jpg,c.jpg”
在数据库“a.jpg,b.jpg,c.jpg”中我想要什么
我试过在谷歌上搜索,但没有结果,有人能帮我解决这个问题吗?谢谢
这是我的密码:
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
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);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
1条答案
按热度按时间gcxthw6b1#
你在设置
$files['file_name'][]
在while loop
在插入数据库之前。你只需要取消第二个呼叫$files['file_name'][] = $updatdName;
下面是你正在做的事情的简化版本。