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

8
  • 1
    If you indent your code it's a lot clearer what's happening Commented Apr 9, 2013 at 16:42
  • 4
    Are you calling mysql_query() function outside your for loop? If yes then you know the solution now... Commented Apr 9, 2013 at 16:43
  • I see you setting $sql, but when do you run that query? Commented Apr 9, 2013 at 16:44
  • 1
    looks like you are actually running the query after the loop. Try $sql .="query here;"; Commented Apr 9, 2013 at 16:46
  • 1
    @Nic: That probably won't work. PHP doesn't like you running multiple queries in one call. Commented Apr 9, 2013 at 16:48

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.