多个文件上传sql/php [英] multiple file upload sql/php
问题描述
我正在尝试上传多个文件,然后在mysql db中插入文件名 我的问题是插入仅存储最后一个文件名的名称
i am trying to upload multiple files and then insert the files names in mysql db my problem is with inserting the names it only store the last file name
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
请注意,所有文件都已成功上传
notice that all the files are uploaded successfully
推荐答案
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
您只是在创建一个字符串并存储一些值.您尚未执行.. 说$ str ="apple";它只是一个声明.我想您已经在循环后执行了查询.假设您有10个文件.循环执行10次,并且$ na具有最后一个插入的文件名.
you are just creating a string and storing some value. you have not executed it .. Say $str = "apple"; Its just a declaration. I presume you have executed the query after the loop. Say you have 10 files. loop gets executed 10 times and $na has the last filename which gets inserted.
Soln:将您的执行查询移至for循环内.
Soln: move your execute query inside the for loop.
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
mysql_query($con,$sql); // note: $con is your connection string
}
}
这篇关于多个文件上传sql/php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!