我需要按照以下格式在数据库中插入多张图片,
09823754257b41f19e24c01471.jpg, 754257b41f19e24c01471422234.jpg,
我编写了以下代码来将值插入数据库
<?php include "dbconnect.php";
if(isset($_POST['property_add'])){
$propTitle = $_POST['title'];
$propSize = $_POST['size'];
$propType = $_POST['type'];
$propLoc = $_POST['location'];
$propStatus = $_POST['status'];
$propPrice = $_POST['price'];
$propDesc = $_POST['propDesc'];
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$temp = explode(".", $_FILES['files']['name'][$key]);
$file_name = rand().uniqid().round(microtime(true)) . '.' . end($temp);
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$desired_dir="../property/".$propTitle."/".$propStatus."/";
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0777, true); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ //rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
if($tmep){
$photos[] = $file_name;
}
}
$files =implode(',', $photos);
$query = "INSERT INTO `property`(`property_name`, `property_size`, `property_type`,`property_loc`, `property_status`, `property_price`, `property_desc`, `property_photos`) VALUES ('$propTitle','$propSize','$propType','$propLoc','$propStatus','$propPrice','$propDesc','$files')";
mysqli_query($conn,$query);
echo "<script>alert('Property Added Successfully')</script>";
header('Location:../dashboard.php?tab=add&mode=success');
}
}
这里的问题是,如果我选择了两个图像 img1
和 img2
但上面的代码为文件生成了以下值
09823754257b41f19e24c01471.jpg、754257b41f19e24c01471422234.jpg、8237542e24c0171422252。 ,
我只想将这两个值插入到数据库中,我不知道为什么会生成第三个值。
最佳答案
你可以像这样使用数组
if($tmep){
$photos[] = $file_name; //put this code place of $photos .= $file_name." ,";
}
和
$files = implode(',', $photos);
这是返回完美的逗号分隔值。
关于php - 使用 for each 循环在 MySQL 数据库中插入多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38992543/