2

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

gen_Eric
  • 223,194
  • 41
  • 299
  • 337

1 Answers1

1
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');";
    }
}

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: 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
    }
}
srinath
  • 2,748
  • 6
  • 35
  • 56