【发布时间】:2015-02-18 00:09:54
【问题描述】:
这是一个脚本,用于在服务器文件夹上上传多个图像并将其路径存储在数据库中,但是图像的路径仅存储在一列中。
例如:我上传了 3 张图片,image1.jpg、image2.jpg、image3.jpg。这些图像应该存储在 3 列中,即 offimage1、offimage2、offimage3。
现在的问题是所有 3 个图像的路径都只存储在 offimage1 下。存储在 offimage1 中的路径看起来像这样,
uploads/image1.jpg*uploads/image1.jpgimage2.jpg*uploads/image1.jpgimage2.jpgimage3.jpg
我希望图像应该以这种方式存储:
uploads/image1.jpg in colum offimage1
uploads/image1.jpgimage2.jpg in colum offimage2
uploads/image1.jpgimage2.jpgimage3.jpg in colum offimage3
html表单
<form enctype="multipart/form-data" action="insert_image.php?id=<?php echo $_GET['id']; ?>" method="post">
<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="submit" id="upload" class="upload"/>
</form>
插入图像.php
<?php
ob_start();
require 'connection.php';
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
//echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
$file_name_all.=$target_path."*";
$filepath = rtrim($file_name_all, '*');
//echo $filepath;
$officeid = $_GET['id'];
$sql = "UPDATE register_office SET offimage='$filepath' WHERE id='$officeid' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
} else {//if file was not moved.
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">***Invalid file Size or Type***</span><br/><br/>';
}
}
header("Location: co_request_sent.php ");
}
mysqli_close($con);
?>
如果有人可以帮助我将不胜感激
【问题讨论】:
-
警告:使用
mysqli时,您应该使用参数化查询和bind_param将用户数据添加到您的查询中。 请勿使用字符串插值来完成此操作,因为您将创建严重的SQL injection bugs。 -
您正在编写一个 SQL 查询,上面写着“SET offimage=blah”,所以它当然只会添加到该列。 PHP 不能只猜测您想要的列名,您需要告诉它查询中的列。但在你这样做之前,试着想想如果他们想上传 5 张图片、10 张或 100 张图片会发生什么......
-
@miken32,我计划将上传数量限制为最多 5 张图片,在 sql 查询中我只使用了一列,因为我无法理解如何在 $filepath 中分隔图片为了保存在不同的列,你能告诉我怎么做吗