我正在尝试将多个图片上传到文件夹并且工作正常。当我试图将图像的名称存储在数据库中时,我遇到了问题。如果我上传只有一个正在工作。如果我上传了多个,我的数据库中只有一个名称。
上传的方式是什么,将带有图像标题的阵列上传到我的数据库?
以下是代码:
<div id="maindiv">
<div id="formdiv">
<h4>Upload Image for </h4>
<form enctype="multipart/form-data" action="" method="post">
<p class="alert alert-info">Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.</p>
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="add_images" id="upload" class="upload"/>
</form>
</div>
这是我的php:
if (isset($_POST['add_images'])) {
$j = 0;
$target_path = "images/";
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['file']['name'][$i]));//store extensions in the variable
$name_of_img = basename($_FILES['file']['name'][$i]);
$target_path = $target_path . $name_of_img;
$j = $j + 1;
if (($_FILES["file"]["size"][$i] < 1000000)
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
print_r($name_of_img);
$query = "UPDATE post SET ";
$query .= "images = '{$name_of_imgs}' ";
$query .= "WHERE post_id = {$the_post_id}";
$update_cruise_img = sqlsrv_query($con, $query);
} else {
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">Wrong file Size or Type</span><br/><br/>';
}
}
}
我尝试创建像$name_of_imgs = json_encode($_POST['file']);
这样的数组但是没有工作
答案 0 :(得分:1)
您需要更新post
循环之外的for
表。
if (isset($_POST['add_images'])) {
$j = 0;
$name_of_imgs = [];
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['file']['name'][$i]));//store extensions in the variable
$name_of_img = basename($_FILES['file']['name'][$i]);
// define target path here so that it won't concat the last value
$target_path = "images/" . $name_of_img;
$j = $j + 1;
if (($_FILES["file"]["size"][$i] < 1000000) && in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
$name_of_imgs[] = $name_of_img;
} else {
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">Wrong file Size or Type</span><br/><br/>';
}
}
// update here
$query = "UPDATE post SET ";
$query .= "images = '" . implode(',', $name_of_imgs) . "' ";
$query .= "WHERE post_id = {$the_post_id}";
$update_cruise_img = sqlsrv_query($con, $query);
}
您可以考虑为图片创建另一个表格。
答案 1 :(得分:0)
您好,您已在上传文件中运行更新查询。它确保this_post_id单一的方式可以用单个文件名更新记录。