我有一张将5张图片上传到服务器文件夹的表单
<form action="co_insert_office_image.php" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Image 1</label>
<div class="col-lg-6">
<input type="file" name="file_img" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Image 2</label>
<div class="col-lg-6">
<input type="file" name="file_img1" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Image 3</label>
<div class="col-lg-6">
<input type="file" name="file_img2" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Image 4</label>
<div class="col-lg-6">
<input type="file" name="file_img3" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Image 5</label>
<div class="col-lg-6">
<input type="file" name="file_img4" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="col-lg-6">
<input type="submit" name="btn_upload" value="Upload">
</div>
</div>
</div>
</form>
co_insert_office_image.php
<?php
include('admin_session.php');
$con=mysqli_connect("localhost","root","","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['btn_upload']))
{
$officeid = $_GET['id'];
echo $officeid;
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
//$filetype = $_FILES["file_img"]["type"];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp,$filepath);
$filetmp1 = $_FILES["file_img1"]["tmp_name"];
$filename1 = $_FILES["file_img1"]["name"];
//$filetype = $_FILES["file_img"]["type"];
$filepath1 = "uploads/".$filename1;
move_uploaded_file($filetmp1,$filepath1);
$filetmp2 = $_FILES["file_img2"]["tmp_name"];
$filename2 = $_FILES["file_img2"]["name"];
//$filetype = $_FILES["file_img"]["type"];
$filepath2 = "uploads/".$filename2;
move_uploaded_file($filetmp2,$filepath2);
$filetmp3 = $_FILES["file_img3"]["tmp_name"];
$filename3 = $_FILES["file_img3"]["name"];
//$filetype = $_FILES["file_img"]["type"];
$filepath3 = "uploads/".$filename3;
move_uploaded_file($filetmp3,$filepath3);
$filetmp4 = $_FILES["file_img4"]["tmp_name"];
$filename4 = $_FILES["file_img4"]["name"];
//$filetype = $_FILES["file_img"]["type"];
$filepath4 = "uploads/".$filename4;
move_uploaded_file($filetmp4,$filepath4);
$sql = "UPDATE register_office set image='".$filepath."' AND image1='".$filepath1."' AND image2='".$filepath2."' AND image3='".$filepath3."' AND image4='".$filepath4."' WHERE id='".$officeid."' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
图像存储在服务器文件夹中,但它们的路径未存储在数据库中。谁能告诉我怎么做?我还想添加检查图像大小和允许的图像扩展类型。任何人都可以用这些观点指导我吗?
答案 0 :(得分:3)
这是您可能喜欢的完整代码
multiupload.php
<html>
<head>
<title>Upload Multiple Images Using jquery and PHP</title>
<!-------Including jQuery from google------>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
<!-------Including CSS File------>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div id="maindiv">
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<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="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
</div>
</div>
</body>
</html>
的script.js
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
的style.css
@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
background-color:white;
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family: 'Droid Sans', sans-serif;
}
#formdiv{
width:500px;
float:left;
text-align: center;
}
form{
padding: 40px 20px;
box-shadow: 0px 0px 10px;
border-radius: 2px;
}
h2{
margin-left: 30px;
}
.upload{
background-color:#ff0000;
border:1px solid #ff0000;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0px green;
box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
color:green;
padding:5px; border:1px dashed #123456;
background-color: #f9ffe5;
}
#upload{
margin-left: 45px;
}
#noerror{
color:green;
text-align: left;
}
#error{
color:red;
text-align: left;
}
#img{
width: 17px;
border: none;
height:17px;
margin-left: -20px;
margin-bottom: 91px;
}
.abcd{
text-align: center;
}
.abcd img{
height:100px;
width:100px;
padding: 5px;
border: 1px solid rgb(232, 222, 189);
}
b{
color:red;
}
#formget{
float:right;
}
upload.php的
<?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/>';
} 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/>';
}
}
}
?>
希望你会发现它很有用
答案 1 :(得分:0)
你的sql语法替换和coma(,)
有错误像:
$sql = "UPDATE register_office set image='".$filepath."', image1='".$filepath1."', image2='".$filepath2."', image3='".$filepath3."', image4='".$filepath4."' WHERE id='".$officeid."' ";
检查此答案如何设置多列:setting multiple column using one update
如果没有上传图片,会发生什么。您应该在if语句中生成SQL /移动图像。
类似于示例(未经测试!):
$sql = "UPDATE $_FILES["file_img4"] SET";
if(isset( $_FILES["file_img4"]) ){
$filetmp4 = $_FILES["file_img4"]["tmp_name"];
$filename4 = $_FILES["file_img4"]["name"];
//$filetype = $_FILES["file_img"]["type"];
$filepath4 = "uploads/".$filename4;
move_uploaded_file($filetmp4,$filepath4);
$sql .= "image4='".$filepath4."' ";
}
// times 5
$sql .= " WHERE id='".$officeid."' ";
答案 2 :(得分:0)
首先,请允许我说代码需要进行转义,并出于安全原因正确处理。
查看PDO和binding您的参数以防止SQL注入和其他潜在问题。
话虽如此,这里的代码有一些变化。请注意,我没有对此进行测试,请检查脚本的语法:php -l scriptName.php
同样在调试时,转储SQL以验证它是否正确,并在MySQL中运行。
<?php
include('admin_session.php');
$con = mysqli_connect("localhost", "root", "", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['btn_upload'])) {
$officeid = $_GET['id'];
echo $officeid;
$files = array(
'file_img',
'file_img1',
'file_img2',
'file_img3',
'file_img4',
);
$sqlData = array();
for ($i = 0; $i <= 4; $i++) {
/*
* The field name: file_img
*/
$inputName = $files[$i];
/*
* Table name: image, image1
*/
$tableField = ($i > 0) ? 'image' . $i : 'image';
/*
* Verify the field data is there
*/
if (isset($_FILES[$inputName])) {
$filetmp = $_FILES[$$inputName]["tmp_name"];
$filename = $_FILES[$$inputName]["name"];
// $filetype = $_FILES["file_img"]["type"];
$filepath = "uploads/" . $filename;
move_uploaded_file($filetmp, $filepath);
/*
* Set the changed image
*/
$sqlData[] = $tableField . ' = "' $filepath . '", ';
}
}
$sql = 'UPDATE register_office SET ';
$sql .= implode(', ', $sqlData);
$sql .= ' WHERE id = ' . $officeid;
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}