如何在我的数据库中连续插入多个图像文件

时间:2016-11-10 08:26:09

标签: php mysql arrays

enter image description here

if(count($_FILES['upload']['name']) > 0){ 

    //Loop through each file 
    for($i=0; $i<count($_FILES['upload']['name']); $i++) { 

        //Get the temp file path 
        $tmpFilePath = $_FILES['upload']['tmp_name'][$i]; 

        //Make sure we have a filepath 
        if($tmpFilePath != ""){ 

            //save the filename 
            $shortname = $_FILES['upload']['name'][$i]; 

            //save the url and the file 
            $filePath = "../img/slider/" .$_FILES['upload']['name'][$i]; 

            //Upload the file into the temp dir             
            if(move_uploaded_file($tmpFilePath, $filePath)) { $files[] = $shortname; 


            } 
        } 
    } 
}

if(is_array($files)){ 

    foreach($files as $file){


        $file1 = "img/slider/" . $file; 
        $query = "INSERT INTO image(image_path,p_number)VALUES('$file1','$number')";
        $result3 = $db->insert($query);
    } 
}

我如何添加内爆?仅作为1条记录存储在我的数据库中。因为这会生成我文件上传的每个文件的记录。

enter image description here

第一张图片是我当前的数据库外观。第二个是我的目标。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

除了大多数情况下不应该是将多个值存储到单个行列中的最佳方法之外,如果插入时已存在p_number(用作主键),则可以更新列: / p>

INSERT INTO image(image_path,p_number)VALUES('$file1','$number')
ON DUPLICATE KEY UPDATE image_path = CONCAT(image_path, ',', $file1);

答案 1 :(得分:0)

根据您的要求,您可以像这样更改代码:

if(is_array($files)){ 
       $completeFileName = implode(',',$files);       
       $query = "INSERT INTO image(image_path,p_number)VALUES('$completeFileName','$number')";
        $result3 = $db->insert($query);
}

答案 2 :(得分:0)

使用PHP Implode

if(is_array($files)){ 
$query = "INSERT INTO image(image_path,p_number)VALUES('".implode(",", $files)."','$number')";
}

旁注:您正在为所有图像存储img/slider。您可以将其删除并作为企鹅,Jellyfish单独存储在您的数据库中与数字和显示图像的位置,您可以将其附加到src。您可以减小表格的大小。