在mysql数据库中按目标文件夹存储多个上传

2hh7jdfx  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(367)

我看到了一堆类似于我的问题,但不完全相同,在某种程度上,我将不得不改变我目前在db上存储文件的方式。
我在第一个文件(getpic.php)中有一个表单:

<form enctype="multipart/form-data" method="POST" action="sendPics.php">
        <font size=4 color=DarkBlue><b>Choose 5 photos of your pet:</b></font><br><br>
    <input type="file" name="file[]" multiple="multiple" /><br><br>
    <input name="send" type="submit" value="Upload photos">

另一个是这个(sendpics.php)

$directory = "Images/";

if(!is_dir($directory)){ 
    echo "Folder does not exist";
}else{
    $file = isset($_FILES['file']) ? $_FILES['file'] : FALSE;
    for ($control = 0; $control < count($file['name']); $control++){

        $destiny = $directory."/".$file['name'][$control];
        if(move_uploaded_file($file['tmp_name'][$control], $destiny)){
            echo "Upload successful<br>"; 
        }else{
            echo "Error uploading the file";
        }   
    }
}

$destiny = "/".$destiny;

mysql中的表如下所示:

Field           | Type       
----------------+------------
 idPetsPics     | int(11)    
 linkProfilePic | varchar(60)
 linkPhoto1     | varchar(60)
 linkPhoto2     | varchar(60)
 linkPhoto3     | varchar(60)
 linkPhoto4     | varchar(60)
 Pet_idPet      | int(11)      //(FK with PetsID on Pet's table)

所以我需要存储上传图片的路径。目前我只能存储在数据库上的第一个,虽然所有的5张图片都成功地到达了目标文件夹。目前我有:

$petID = $_SESSION['petID']; // obtained from a third file (queries to insert date into Pet)
require_once('dbConnection.php');

$insertPetPic = "INSERT INTO petPic (idPetsPics, linkProfilePic, Pet_idPet) VALUES (NULL, '$destiny', $petID[0])";
mysqli_query($conn, $insertFotoPet);

如何更改代码以存储所有5个路径?

bt1cpqcv

bt1cpqcv1#

对于成功移动的每个图像,需要将图像的路径存储在某个位置,例如 $paths 数组:

$directory = "Images/";
$paths = array();

if(!is_dir($directory)){ 
    echo "Folder does not exist";
}else{
    $file = isset($_FILES['file']) ? $_FILES['file'] : FALSE;
    for ($control = 0; $control < count($file['name']); $control++){

        $destiny = $directory."/".$file['name'][$control];
        if(move_uploaded_file($file['tmp_name'][$control], $destiny)){
            $paths[] = $destiny;
            echo "Upload successful<br>"; 
        }else{
            echo "Error uploading the file";
        }   
    }
}

然后在查询中使用数组中的路径:

$insertPetPic = "INSERT INTO petPic (idPetsPics, linkProfilePic, linkPhoto1, linkPhoto2, linkPhoto3, linkPhoto4, Pet_idPet) VALUES (NULL, '$paths[0]', '$paths[1]', '$paths[2]', '$paths[3]', '$paths[4]', $petID[0])";

相关问题