我看到了一系列与我的问题类似但又不太相同的问题,以某种方式,我必须更改当前在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)
所以我需要存储上传照片的路径。目前,我只能将第一个存储在DB上,尽管所有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条路径?
答案 0 :(得分:1)
对于成功移动的每个图像,您需要将图像的路径存储在某个地方,例如存储在$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])";